diff --git a/cli/src/commands.rs b/cli/src/commands.rs index 71b7ba2..dfd1b8f 100644 --- a/cli/src/commands.rs +++ b/cli/src/commands.rs @@ -22,7 +22,17 @@ pub(crate) enum Command { /// Send lbtc and receive btc lightning through a swap SendPayment { /// Invoice which has to be paid - bolt11: String, + #[arg(long)] + bolt11: Option, + + /// Either BIP21 URI or Liquid address we intend to pay to + #[arg(long)] + address: Option, + + /// The amount in satoshi to pay, in case of a direct Liquid address + /// or amount-less BIP21 + #[arg(short, long)] + amount_sat: Option, /// Delay for the send, in seconds #[arg(short, long)] @@ -46,18 +56,19 @@ pub(crate) enum Command { }, /// Receive lbtc and send btc through a swap ReceivePayment { + /// The method to use when receiving. Either "lightning", "bitcoin" or "liquid" + #[arg(short = 'm', long = "method")] + payment_method: Option, + /// Amount the payer will send, in satoshi - payer_amount_sat: u64, + /// If not specified, it will generate a BIP21 URI/Liquid address with no amount + #[arg(short, long)] + payer_amount_sat: Option, /// Optional description for the invoice #[clap(short = 'd', long = "description")] description: Option, }, - /// Receive lbtc and send btc onchain through a swap - ReceiveOnchainPayment { - /// Amount the payer will send, in satoshi - payer_amount_sat: u64, - }, /// Generates an URL to buy bitcoin from a 3rd party provider BuyBitcoin { provider: BuyBitcoinProvider, @@ -200,32 +211,49 @@ pub(crate) async fn handle_command( ) -> Result { Ok(match command { Command::ReceivePayment { + payment_method, payer_amount_sat, description, } => { - let prepare_res = sdk - .prepare_receive_payment(&PrepareReceivePaymentRequest { payer_amount_sat }) + let prepare_response = sdk + .prepare_receive_payment(&PrepareReceiveRequest { + payer_amount_sat, + payment_method: payment_method.unwrap_or(PaymentMethod::Lightning), + }) .await?; wait_confirmation!( format!( "Fees: {} sat. Are the fees acceptable? (y/N) ", - prepare_res.fees_sat + prepare_response.fees_sat ), "Payment receive halted" ); let response = sdk .receive_payment(&ReceivePaymentRequest { - prepare_res, + prepare_response, description, }) .await?; - let invoice = response.invoice.clone(); - let mut result = command_result!(response); + let mut result = command_result!(&response); result.push('\n'); - result.push_str(&build_qr_text(&invoice)); + + match parse(&response.destination).await? { + InputType::Bolt11 { invoice } => result.push_str(&build_qr_text(&invoice.bolt11)), + InputType::LiquidAddress { address } => { + result.push_str(&build_qr_text(&address.to_uri().map_err(|e| { + anyhow::anyhow!("Could not build BIP21 from address data: {e:?}") + })?)) + } + InputType::BitcoinAddress { address } => { + result.push_str(&build_qr_text(&address.to_uri().map_err(|e| { + anyhow::anyhow!("Could not build BIP21 from address data: {e:?}") + })?)) + } + _ => {} + } result } Command::FetchLightningLimits => { @@ -236,9 +264,32 @@ pub(crate) async fn handle_command( let limits = sdk.fetch_onchain_limits().await?; command_result!(limits) } - Command::SendPayment { bolt11, delay } => { + Command::SendPayment { + bolt11, + address, + amount_sat, + delay, + } => { + let destination = match (bolt11, address) { + (None, None) => { + return Err(anyhow::anyhow!( + "Must specify either a `bolt11` invoice or a direct/BIP21 `address`." + )) + } + (Some(bolt11), None) => bolt11, + (None, Some(address)) => address, + (Some(_), Some(_)) => { + return Err(anyhow::anyhow!( + "Cannot specify both `bolt11` and `address` at the same time." + )) + } + }; + let prepare_response = sdk - .prepare_send_payment(&PrepareSendRequest { invoice: bolt11 }) + .prepare_send_payment(&PrepareSendRequest { + destination, + amount_sat, + }) .await?; wait_confirmation!( @@ -249,17 +300,20 @@ pub(crate) async fn handle_command( "Payment send halted" ); + let send_payment_req = SendPaymentRequest { + prepare_response: prepare_response.clone(), + }; + if let Some(delay) = delay { let sdk_cloned = sdk.clone(); - let prepare_cloned = prepare_response.clone(); tokio::spawn(async move { thread::sleep(Duration::from_secs(delay)); - sdk_cloned.send_payment(&prepare_cloned).await.unwrap(); + sdk_cloned.send_payment(&send_payment_req).await.unwrap(); }); command_result!(prepare_response) } else { - let response = sdk.send_payment(&prepare_response).await?; + let response = sdk.send_payment(&send_payment_req).await?; command_result!(response) } } @@ -268,7 +322,7 @@ pub(crate) async fn handle_command( receiver_amount_sat, sat_per_vbyte, } => { - let prepare_res = sdk + let prepare_response = sdk .prepare_pay_onchain(&PreparePayOnchainRequest { receiver_amount_sat, sat_per_vbyte, @@ -278,7 +332,7 @@ pub(crate) async fn handle_command( wait_confirmation!( format!( "Fees: {} sat (incl claim fee: {} sat). Are the fees acceptable? (y/N) ", - prepare_res.total_fees_sat, prepare_res.claim_fees_sat + prepare_response.total_fees_sat, prepare_response.claim_fees_sat ), "Payment send halted" ); @@ -286,37 +340,16 @@ pub(crate) async fn handle_command( let response = sdk .pay_onchain(&PayOnchainRequest { address, - prepare_res, + prepare_response, }) .await?; command_result!(response) } - Command::ReceiveOnchainPayment { payer_amount_sat } => { - let prepare_res = sdk - .prepare_receive_onchain(&PrepareReceiveOnchainRequest { payer_amount_sat }) - .await?; - - wait_confirmation!( - format!( - "Fees: {} sat. Are the fees acceptable? (y/N) ", - prepare_res.fees_sat - ), - "Payment receive halted" - ); - - let response = sdk.receive_onchain(&prepare_res).await?; - let bip21 = response.bip21.clone(); - - let mut result = command_result!(response); - result.push('\n'); - result.push_str(&build_qr_text(&bip21)); - result - } Command::BuyBitcoin { provider, amount_sat, } => { - let prepare_res = sdk + let prepare_response = sdk .prepare_buy_bitcoin(&PrepareBuyBitcoinRequest { provider, amount_sat, @@ -326,14 +359,14 @@ pub(crate) async fn handle_command( wait_confirmation!( format!( "Fees: {} sat. Are the fees acceptable? (y/N) ", - prepare_res.fees_sat + prepare_response.fees_sat ), "Buy Bitcoin halted" ); let url = sdk .buy_bitcoin(&BuyBitcoinRequest { - prepare_res, + prepare_response, redirect_url: None, }) .await?; diff --git a/lib/bindings/langs/android/.gitignore b/lib/bindings/langs/android/.gitignore index 24c7763..7e7fed0 100644 --- a/lib/bindings/langs/android/.gitignore +++ b/lib/bindings/langs/android/.gitignore @@ -45,4 +45,5 @@ gen-external-apklibs # End of https://www.toptal.com/developers/gitignore/api/android lib/src/main/jniLibs/ +lib/src/main/kotlin/breez_sdk_liquid.kt lib/src/main/kotlin/breez_sdk_liquid/breez_sdk_liquid.kt \ No newline at end of file diff --git a/lib/bindings/langs/flutter/breez_sdk_liquid/include/breez_sdk_liquid.h b/lib/bindings/langs/flutter/breez_sdk_liquid/include/breez_sdk_liquid.h index 062b60b..cf3cccb 100644 --- a/lib/bindings/langs/flutter/breez_sdk_liquid/include/breez_sdk_liquid.h +++ b/lib/bindings/langs/flutter/breez_sdk_liquid/include/breez_sdk_liquid.h @@ -53,7 +53,7 @@ typedef struct wire_cst_prepare_buy_bitcoin_response { } wire_cst_prepare_buy_bitcoin_response; typedef struct wire_cst_buy_bitcoin_request { - struct wire_cst_prepare_buy_bitcoin_response prepare_res; + struct wire_cst_prepare_buy_bitcoin_response prepare_response; struct wire_cst_list_prim_u_8_strict *redirect_url; } wire_cst_buy_bitcoin_request; @@ -119,7 +119,7 @@ typedef struct wire_cst_prepare_pay_onchain_response { typedef struct wire_cst_pay_onchain_request { struct wire_cst_list_prim_u_8_strict *address; - struct wire_cst_prepare_pay_onchain_response prepare_res; + struct wire_cst_prepare_pay_onchain_response prepare_response; } wire_cst_pay_onchain_request; typedef struct wire_cst_prepare_buy_bitcoin_request { @@ -132,13 +132,10 @@ typedef struct wire_cst_prepare_pay_onchain_request { uint32_t *sat_per_vbyte; } wire_cst_prepare_pay_onchain_request; -typedef struct wire_cst_prepare_receive_onchain_request { - uint64_t payer_amount_sat; -} wire_cst_prepare_receive_onchain_request; - -typedef struct wire_cst_prepare_receive_payment_request { - uint64_t payer_amount_sat; -} wire_cst_prepare_receive_payment_request; +typedef struct wire_cst_prepare_receive_request { + uint64_t *payer_amount_sat; + int32_t payment_method; +} wire_cst_prepare_receive_request; typedef struct wire_cst_prepare_refund_request { struct wire_cst_list_prim_u_8_strict *swap_address; @@ -147,22 +144,19 @@ typedef struct wire_cst_prepare_refund_request { } wire_cst_prepare_refund_request; typedef struct wire_cst_prepare_send_request { - struct wire_cst_list_prim_u_8_strict *invoice; + struct wire_cst_list_prim_u_8_strict *destination; + uint64_t *amount_sat; } wire_cst_prepare_send_request; -typedef struct wire_cst_prepare_receive_onchain_response { - uint64_t payer_amount_sat; +typedef struct wire_cst_prepare_receive_response { + int32_t payment_method; + uint64_t *payer_amount_sat; uint64_t fees_sat; -} wire_cst_prepare_receive_onchain_response; - -typedef struct wire_cst_prepare_receive_payment_response { - uint64_t payer_amount_sat; - uint64_t fees_sat; -} wire_cst_prepare_receive_payment_response; +} wire_cst_prepare_receive_response; typedef struct wire_cst_receive_payment_request { struct wire_cst_list_prim_u_8_strict *description; - struct wire_cst_prepare_receive_payment_response prepare_res; + struct wire_cst_prepare_receive_response prepare_response; } wire_cst_receive_payment_request; typedef struct wire_cst_refund_request { @@ -175,28 +169,126 @@ typedef struct wire_cst_restore_request { struct wire_cst_list_prim_u_8_strict *backup_path; } wire_cst_restore_request; +typedef struct wire_cst_liquid_address_data { + struct wire_cst_list_prim_u_8_strict *address; + int32_t network; + struct wire_cst_list_prim_u_8_strict *asset_id; + uint64_t *amount_sat; + struct wire_cst_list_prim_u_8_strict *label; + struct wire_cst_list_prim_u_8_strict *message; +} wire_cst_liquid_address_data; + +typedef struct wire_cst_SendDestination_LiquidAddress { + struct wire_cst_liquid_address_data *address_data; +} wire_cst_SendDestination_LiquidAddress; + +typedef struct wire_cst_route_hint_hop { + struct wire_cst_list_prim_u_8_strict *src_node_id; + uint64_t short_channel_id; + uint32_t fees_base_msat; + uint32_t fees_proportional_millionths; + uint64_t cltv_expiry_delta; + uint64_t *htlc_minimum_msat; + uint64_t *htlc_maximum_msat; +} wire_cst_route_hint_hop; + +typedef struct wire_cst_list_route_hint_hop { + struct wire_cst_route_hint_hop *ptr; + int32_t len; +} wire_cst_list_route_hint_hop; + +typedef struct wire_cst_route_hint { + struct wire_cst_list_route_hint_hop *hops; +} wire_cst_route_hint; + +typedef struct wire_cst_list_route_hint { + struct wire_cst_route_hint *ptr; + int32_t len; +} wire_cst_list_route_hint; + +typedef struct wire_cst_ln_invoice { + struct wire_cst_list_prim_u_8_strict *bolt11; + int32_t network; + struct wire_cst_list_prim_u_8_strict *payee_pubkey; + struct wire_cst_list_prim_u_8_strict *payment_hash; + struct wire_cst_list_prim_u_8_strict *description; + struct wire_cst_list_prim_u_8_strict *description_hash; + uint64_t *amount_msat; + uint64_t timestamp; + uint64_t expiry; + struct wire_cst_list_route_hint *routing_hints; + struct wire_cst_list_prim_u_8_strict *payment_secret; + uint64_t min_final_cltv_expiry_delta; +} wire_cst_ln_invoice; + +typedef struct wire_cst_SendDestination_Bolt11 { + struct wire_cst_ln_invoice *invoice; +} wire_cst_SendDestination_Bolt11; + +typedef union SendDestinationKind { + struct wire_cst_SendDestination_LiquidAddress LiquidAddress; + struct wire_cst_SendDestination_Bolt11 Bolt11; +} SendDestinationKind; + +typedef struct wire_cst_send_destination { + int32_t tag; + union SendDestinationKind kind; +} wire_cst_send_destination; + typedef struct wire_cst_prepare_send_response { - struct wire_cst_list_prim_u_8_strict *invoice; + struct wire_cst_send_destination destination; uint64_t fees_sat; } wire_cst_prepare_send_response; +typedef struct wire_cst_send_payment_request { + struct wire_cst_prepare_send_response prepare_response; +} wire_cst_send_payment_request; + typedef struct wire_cst_binding_event_listener { struct wire_cst_list_prim_u_8_strict *stream; } wire_cst_binding_event_listener; -typedef struct wire_cst_payment { - struct wire_cst_list_prim_u_8_strict *tx_id; +typedef struct wire_cst_PaymentDetails_Lightning { struct wire_cst_list_prim_u_8_strict *swap_id; - uint32_t timestamp; - uint64_t amount_sat; - uint64_t fees_sat; + struct wire_cst_list_prim_u_8_strict *description; struct wire_cst_list_prim_u_8_strict *preimage; struct wire_cst_list_prim_u_8_strict *bolt11; + struct wire_cst_list_prim_u_8_strict *refund_tx_id; + uint64_t *refund_tx_amount_sat; +} wire_cst_PaymentDetails_Lightning; + +typedef struct wire_cst_PaymentDetails_Liquid { + struct wire_cst_list_prim_u_8_strict *destination; + struct wire_cst_list_prim_u_8_strict *description; +} wire_cst_PaymentDetails_Liquid; + +typedef struct wire_cst_PaymentDetails_Bitcoin { + struct wire_cst_list_prim_u_8_strict *swap_id; struct wire_cst_list_prim_u_8_strict *description; struct wire_cst_list_prim_u_8_strict *refund_tx_id; uint64_t *refund_tx_amount_sat; +} wire_cst_PaymentDetails_Bitcoin; + +typedef union PaymentDetailsKind { + struct wire_cst_PaymentDetails_Lightning Lightning; + struct wire_cst_PaymentDetails_Liquid Liquid; + struct wire_cst_PaymentDetails_Bitcoin Bitcoin; +} PaymentDetailsKind; + +typedef struct wire_cst_payment_details { + int32_t tag; + union PaymentDetailsKind kind; +} wire_cst_payment_details; + +typedef struct wire_cst_payment { + struct wire_cst_list_prim_u_8_strict *destination; + struct wire_cst_list_prim_u_8_strict *tx_id; + uint32_t timestamp; + uint64_t amount_sat; + uint64_t fees_sat; int32_t payment_type; int32_t status; + struct wire_cst_payment_details *details; } wire_cst_payment; typedef struct wire_cst_SdkEvent_PaymentFailed { @@ -284,54 +376,6 @@ typedef struct wire_cst_bitcoin_address_data { struct wire_cst_list_prim_u_8_strict *message; } wire_cst_bitcoin_address_data; -typedef struct wire_cst_liquid_address_data { - struct wire_cst_list_prim_u_8_strict *address; - int32_t network; - struct wire_cst_list_prim_u_8_strict *asset_id; - uint64_t *amount_sat; - struct wire_cst_list_prim_u_8_strict *label; - struct wire_cst_list_prim_u_8_strict *message; -} wire_cst_liquid_address_data; - -typedef struct wire_cst_route_hint_hop { - struct wire_cst_list_prim_u_8_strict *src_node_id; - uint64_t short_channel_id; - uint32_t fees_base_msat; - uint32_t fees_proportional_millionths; - uint64_t cltv_expiry_delta; - uint64_t *htlc_minimum_msat; - uint64_t *htlc_maximum_msat; -} wire_cst_route_hint_hop; - -typedef struct wire_cst_list_route_hint_hop { - struct wire_cst_route_hint_hop *ptr; - int32_t len; -} wire_cst_list_route_hint_hop; - -typedef struct wire_cst_route_hint { - struct wire_cst_list_route_hint_hop *hops; -} wire_cst_route_hint; - -typedef struct wire_cst_list_route_hint { - struct wire_cst_route_hint *ptr; - int32_t len; -} wire_cst_list_route_hint; - -typedef struct wire_cst_ln_invoice { - struct wire_cst_list_prim_u_8_strict *bolt11; - int32_t network; - struct wire_cst_list_prim_u_8_strict *payee_pubkey; - struct wire_cst_list_prim_u_8_strict *payment_hash; - struct wire_cst_list_prim_u_8_strict *description; - struct wire_cst_list_prim_u_8_strict *description_hash; - uint64_t *amount_msat; - uint64_t timestamp; - uint64_t expiry; - struct wire_cst_list_route_hint *routing_hints; - struct wire_cst_list_prim_u_8_strict *payment_secret; - uint64_t min_final_cltv_expiry_delta; -} wire_cst_ln_invoice; - typedef struct wire_cst_ln_url_error_data { struct wire_cst_list_prim_u_8_strict *reason; } wire_cst_ln_url_error_data; @@ -721,6 +765,14 @@ typedef struct wire_cst_onchain_payment_limits_response { struct wire_cst_limits receive; } wire_cst_onchain_payment_limits_response; +typedef struct wire_cst_PaymentError_AmountMissing { + struct wire_cst_list_prim_u_8_strict *err; +} wire_cst_PaymentError_AmountMissing; + +typedef struct wire_cst_PaymentError_InvalidNetwork { + struct wire_cst_list_prim_u_8_strict *err; +} wire_cst_PaymentError_InvalidNetwork; + typedef struct wire_cst_PaymentError_Generic { struct wire_cst_list_prim_u_8_strict *err; } wire_cst_PaymentError_Generic; @@ -751,6 +803,8 @@ typedef struct wire_cst_PaymentError_SignerError { } wire_cst_PaymentError_SignerError; typedef union PaymentErrorKind { + struct wire_cst_PaymentError_AmountMissing AmountMissing; + struct wire_cst_PaymentError_InvalidNetwork InvalidNetwork; struct wire_cst_PaymentError_Generic Generic; struct wire_cst_PaymentError_InvalidInvoice InvalidInvoice; struct wire_cst_PaymentError_LwkError LwkError; @@ -771,14 +825,8 @@ typedef struct wire_cst_prepare_refund_response { struct wire_cst_list_prim_u_8_strict *refund_tx_id; } wire_cst_prepare_refund_response; -typedef struct wire_cst_receive_onchain_response { - struct wire_cst_list_prim_u_8_strict *address; - struct wire_cst_list_prim_u_8_strict *bip21; -} wire_cst_receive_onchain_response; - typedef struct wire_cst_receive_payment_response { - struct wire_cst_list_prim_u_8_strict *id; - struct wire_cst_list_prim_u_8_strict *invoice; + struct wire_cst_list_prim_u_8_strict *destination; } wire_cst_receive_payment_response; typedef struct wire_cst_recommended_fees { @@ -877,13 +925,9 @@ void frbgen_breez_liquid_wire__crate__bindings__BindingLiquidSdk_prepare_pay_onc uintptr_t that, struct wire_cst_prepare_pay_onchain_request *req); -void frbgen_breez_liquid_wire__crate__bindings__BindingLiquidSdk_prepare_receive_onchain(int64_t port_, - uintptr_t that, - struct wire_cst_prepare_receive_onchain_request *req); - void frbgen_breez_liquid_wire__crate__bindings__BindingLiquidSdk_prepare_receive_payment(int64_t port_, uintptr_t that, - struct wire_cst_prepare_receive_payment_request *req); + struct wire_cst_prepare_receive_request *req); void frbgen_breez_liquid_wire__crate__bindings__BindingLiquidSdk_prepare_refund(int64_t port_, uintptr_t that, @@ -893,10 +937,6 @@ void frbgen_breez_liquid_wire__crate__bindings__BindingLiquidSdk_prepare_send_pa uintptr_t that, struct wire_cst_prepare_send_request *req); -void frbgen_breez_liquid_wire__crate__bindings__BindingLiquidSdk_receive_onchain(int64_t port_, - uintptr_t that, - struct wire_cst_prepare_receive_onchain_response *req); - void frbgen_breez_liquid_wire__crate__bindings__BindingLiquidSdk_receive_payment(int64_t port_, uintptr_t that, struct wire_cst_receive_payment_request *req); @@ -916,7 +956,7 @@ WireSyncRust2DartDco frbgen_breez_liquid_wire__crate__bindings__BindingLiquidSdk void frbgen_breez_liquid_wire__crate__bindings__BindingLiquidSdk_send_payment(int64_t port_, uintptr_t that, - struct wire_cst_prepare_send_response *req); + struct wire_cst_send_payment_request *req); void frbgen_breez_liquid_wire__crate__bindings__BindingLiquidSdk_sync(int64_t port_, uintptr_t that); @@ -990,22 +1030,18 @@ struct wire_cst_pay_onchain_request *frbgen_breez_liquid_cst_new_box_autoadd_pay struct wire_cst_payment *frbgen_breez_liquid_cst_new_box_autoadd_payment(void); +struct wire_cst_payment_details *frbgen_breez_liquid_cst_new_box_autoadd_payment_details(void); + struct wire_cst_prepare_buy_bitcoin_request *frbgen_breez_liquid_cst_new_box_autoadd_prepare_buy_bitcoin_request(void); struct wire_cst_prepare_pay_onchain_request *frbgen_breez_liquid_cst_new_box_autoadd_prepare_pay_onchain_request(void); -struct wire_cst_prepare_receive_onchain_request *frbgen_breez_liquid_cst_new_box_autoadd_prepare_receive_onchain_request(void); - -struct wire_cst_prepare_receive_onchain_response *frbgen_breez_liquid_cst_new_box_autoadd_prepare_receive_onchain_response(void); - -struct wire_cst_prepare_receive_payment_request *frbgen_breez_liquid_cst_new_box_autoadd_prepare_receive_payment_request(void); +struct wire_cst_prepare_receive_request *frbgen_breez_liquid_cst_new_box_autoadd_prepare_receive_request(void); struct wire_cst_prepare_refund_request *frbgen_breez_liquid_cst_new_box_autoadd_prepare_refund_request(void); struct wire_cst_prepare_send_request *frbgen_breez_liquid_cst_new_box_autoadd_prepare_send_request(void); -struct wire_cst_prepare_send_response *frbgen_breez_liquid_cst_new_box_autoadd_prepare_send_response(void); - struct wire_cst_receive_payment_request *frbgen_breez_liquid_cst_new_box_autoadd_receive_payment_request(void); struct wire_cst_refund_request *frbgen_breez_liquid_cst_new_box_autoadd_refund_request(void); @@ -1014,6 +1050,8 @@ struct wire_cst_restore_request *frbgen_breez_liquid_cst_new_box_autoadd_restore struct wire_cst_sdk_event *frbgen_breez_liquid_cst_new_box_autoadd_sdk_event(void); +struct wire_cst_send_payment_request *frbgen_breez_liquid_cst_new_box_autoadd_send_payment_request(void); + struct wire_cst_success_action_processed *frbgen_breez_liquid_cst_new_box_autoadd_success_action_processed(void); struct wire_cst_symbol *frbgen_breez_liquid_cst_new_box_autoadd_symbol(void); @@ -1069,18 +1107,17 @@ static int64_t dummy_method_to_enforce_bundling(void) { dummy_var ^= ((int64_t) (void*) frbgen_breez_liquid_cst_new_box_autoadd_message_success_action_data); dummy_var ^= ((int64_t) (void*) frbgen_breez_liquid_cst_new_box_autoadd_pay_onchain_request); dummy_var ^= ((int64_t) (void*) frbgen_breez_liquid_cst_new_box_autoadd_payment); + dummy_var ^= ((int64_t) (void*) frbgen_breez_liquid_cst_new_box_autoadd_payment_details); dummy_var ^= ((int64_t) (void*) frbgen_breez_liquid_cst_new_box_autoadd_prepare_buy_bitcoin_request); dummy_var ^= ((int64_t) (void*) frbgen_breez_liquid_cst_new_box_autoadd_prepare_pay_onchain_request); - dummy_var ^= ((int64_t) (void*) frbgen_breez_liquid_cst_new_box_autoadd_prepare_receive_onchain_request); - dummy_var ^= ((int64_t) (void*) frbgen_breez_liquid_cst_new_box_autoadd_prepare_receive_onchain_response); - dummy_var ^= ((int64_t) (void*) frbgen_breez_liquid_cst_new_box_autoadd_prepare_receive_payment_request); + dummy_var ^= ((int64_t) (void*) frbgen_breez_liquid_cst_new_box_autoadd_prepare_receive_request); dummy_var ^= ((int64_t) (void*) frbgen_breez_liquid_cst_new_box_autoadd_prepare_refund_request); dummy_var ^= ((int64_t) (void*) frbgen_breez_liquid_cst_new_box_autoadd_prepare_send_request); - dummy_var ^= ((int64_t) (void*) frbgen_breez_liquid_cst_new_box_autoadd_prepare_send_response); dummy_var ^= ((int64_t) (void*) frbgen_breez_liquid_cst_new_box_autoadd_receive_payment_request); dummy_var ^= ((int64_t) (void*) frbgen_breez_liquid_cst_new_box_autoadd_refund_request); dummy_var ^= ((int64_t) (void*) frbgen_breez_liquid_cst_new_box_autoadd_restore_request); dummy_var ^= ((int64_t) (void*) frbgen_breez_liquid_cst_new_box_autoadd_sdk_event); + dummy_var ^= ((int64_t) (void*) frbgen_breez_liquid_cst_new_box_autoadd_send_payment_request); dummy_var ^= ((int64_t) (void*) frbgen_breez_liquid_cst_new_box_autoadd_success_action_processed); dummy_var ^= ((int64_t) (void*) frbgen_breez_liquid_cst_new_box_autoadd_symbol); dummy_var ^= ((int64_t) (void*) frbgen_breez_liquid_cst_new_box_autoadd_u_32); @@ -1116,11 +1153,9 @@ static int64_t dummy_method_to_enforce_bundling(void) { dummy_var ^= ((int64_t) (void*) frbgen_breez_liquid_wire__crate__bindings__BindingLiquidSdk_pay_onchain); dummy_var ^= ((int64_t) (void*) frbgen_breez_liquid_wire__crate__bindings__BindingLiquidSdk_prepare_buy_bitcoin); dummy_var ^= ((int64_t) (void*) frbgen_breez_liquid_wire__crate__bindings__BindingLiquidSdk_prepare_pay_onchain); - dummy_var ^= ((int64_t) (void*) frbgen_breez_liquid_wire__crate__bindings__BindingLiquidSdk_prepare_receive_onchain); dummy_var ^= ((int64_t) (void*) frbgen_breez_liquid_wire__crate__bindings__BindingLiquidSdk_prepare_receive_payment); dummy_var ^= ((int64_t) (void*) frbgen_breez_liquid_wire__crate__bindings__BindingLiquidSdk_prepare_refund); dummy_var ^= ((int64_t) (void*) frbgen_breez_liquid_wire__crate__bindings__BindingLiquidSdk_prepare_send_payment); - dummy_var ^= ((int64_t) (void*) frbgen_breez_liquid_wire__crate__bindings__BindingLiquidSdk_receive_onchain); dummy_var ^= ((int64_t) (void*) frbgen_breez_liquid_wire__crate__bindings__BindingLiquidSdk_receive_payment); dummy_var ^= ((int64_t) (void*) frbgen_breez_liquid_wire__crate__bindings__BindingLiquidSdk_recommended_fees); dummy_var ^= ((int64_t) (void*) frbgen_breez_liquid_wire__crate__bindings__BindingLiquidSdk_refund); diff --git a/lib/bindings/src/breez_sdk_liquid.udl b/lib/bindings/src/breez_sdk_liquid.udl index c5d83da..bc3d0bc 100644 --- a/lib/bindings/src/breez_sdk_liquid.udl +++ b/lib/bindings/src/breez_sdk_liquid.udl @@ -278,10 +278,12 @@ enum PaymentError { "AlreadyPaid", "PaymentInProgress", "AmountOutOfRange", + "AmountMissing", "Generic", "InvalidOrExpiredFees", "InsufficientFunds", "InvalidInvoice", + "InvalidNetwork", "InvalidPreimage", "LwkError", "PairsNotFound", @@ -323,35 +325,53 @@ dictionary GetInfoResponse { }; dictionary PrepareSendRequest { - string invoice; + string destination; + u64? amount_sat; +}; + +[Enum] +interface SendDestination { + LiquidAddress(LiquidAddressData address_data); + Bolt11(LNInvoice invoice); }; dictionary PrepareSendResponse { - string invoice; + SendDestination destination; u64 fees_sat; }; +dictionary SendPaymentRequest { + PrepareSendResponse prepare_response; +}; + dictionary SendPaymentResponse { Payment payment; }; -dictionary PrepareReceivePaymentRequest { - u64 payer_amount_sat; +enum PaymentMethod { + "Lightning", + "BitcoinAddress", + "LiquidAddress", }; -dictionary PrepareReceivePaymentResponse { - u64 payer_amount_sat; +dictionary PrepareReceiveRequest { + u64? payer_amount_sat; + PaymentMethod payment_method; +}; + +dictionary PrepareReceiveResponse { + u64? payer_amount_sat; + PaymentMethod payment_method; u64 fees_sat; }; dictionary ReceivePaymentRequest { - PrepareReceivePaymentResponse prepare_res; + PrepareReceiveResponse prepare_response; string? description = null; }; dictionary ReceivePaymentResponse { - string id; - string invoice; + string destination; }; dictionary Limits { @@ -383,21 +403,7 @@ dictionary PreparePayOnchainResponse { dictionary PayOnchainRequest { string address; - PreparePayOnchainResponse prepare_res; -}; - -dictionary PrepareReceiveOnchainRequest { - u64 payer_amount_sat; -}; - -dictionary PrepareReceiveOnchainResponse { - u64 payer_amount_sat; - u64 fees_sat; -}; - -dictionary ReceiveOnchainResponse { - string address; - string bip21; + PreparePayOnchainResponse prepare_response; }; enum BuyBitcoinProvider { @@ -416,7 +422,7 @@ dictionary PrepareBuyBitcoinResponse { }; dictionary BuyBitcoinRequest { - PrepareBuyBitcoinResponse prepare_res; + PrepareBuyBitcoinResponse prepare_response; string? redirect_url = null; }; @@ -436,19 +442,22 @@ dictionary ListPaymentsRequest { u32? limit = null; }; +[Enum] +interface PaymentDetails { + Lightning(string swap_id, string description, string? preimage, string? bolt11, string? refund_tx_id, u64? refund_tx_amount_sat); + Liquid(string destination, string description); + Bitcoin(string swap_id, string description, string? refund_tx_id, u64? refund_tx_amount_sat); +}; + dictionary Payment { + string? destination; + string? tx_id = null; u32 timestamp; u64 amount_sat; u64 fees_sat; PaymentType payment_type; PaymentState status; - string description; - string? tx_id = null; - string? swap_id = null; - string? preimage = null; - string? bolt11 = null; - string? refund_tx_id = null; - u64? refund_tx_amount_sat = null; + PaymentDetails? details; }; enum PaymentType { @@ -556,10 +565,10 @@ interface BindingLiquidSdk { PrepareSendResponse prepare_send_payment(PrepareSendRequest req); [Throws=PaymentError] - SendPaymentResponse send_payment(PrepareSendResponse req); + SendPaymentResponse send_payment(SendPaymentRequest req); [Throws=PaymentError] - PrepareReceivePaymentResponse prepare_receive_payment(PrepareReceivePaymentRequest req); + PrepareReceiveResponse prepare_receive_payment(PrepareReceiveRequest req); [Throws=PaymentError] ReceivePaymentResponse receive_payment(ReceivePaymentRequest req); @@ -576,12 +585,6 @@ interface BindingLiquidSdk { [Throws=PaymentError] SendPaymentResponse pay_onchain(PayOnchainRequest req); - [Throws=PaymentError] - PrepareReceiveOnchainResponse prepare_receive_onchain(PrepareReceiveOnchainRequest req); - - [Throws=PaymentError] - ReceiveOnchainResponse receive_onchain(PrepareReceiveOnchainResponse req); - [Throws=PaymentError] PrepareBuyBitcoinResponse prepare_buy_bitcoin(PrepareBuyBitcoinRequest req); diff --git a/lib/bindings/src/lib.rs b/lib/bindings/src/lib.rs index ba3b437..47b6104 100644 --- a/lib/bindings/src/lib.rs +++ b/lib/bindings/src/lib.rs @@ -94,15 +94,15 @@ impl BindingLiquidSdk { pub fn send_payment( &self, - req: PrepareSendResponse, + req: SendPaymentRequest, ) -> Result { rt().block_on(self.sdk.send_payment(&req)) } pub fn prepare_receive_payment( &self, - req: PrepareReceivePaymentRequest, - ) -> Result { + req: PrepareReceiveRequest, + ) -> Result { rt().block_on(self.sdk.prepare_receive_payment(&req)) } @@ -132,20 +132,6 @@ impl BindingLiquidSdk { rt().block_on(self.sdk.pay_onchain(&req)) } - pub fn prepare_receive_onchain( - &self, - req: PrepareReceiveOnchainRequest, - ) -> Result { - rt().block_on(self.sdk.prepare_receive_onchain(&req)) - } - - pub fn receive_onchain( - &self, - req: PrepareReceiveOnchainResponse, - ) -> Result { - rt().block_on(self.sdk.receive_onchain(&req)) - } - pub fn prepare_buy_bitcoin( &self, req: PrepareBuyBitcoinRequest, diff --git a/lib/core/Cargo.toml b/lib/core/Cargo.toml index e9b1adc..0305e6c 100644 --- a/lib/core/Cargo.toml +++ b/lib/core/Cargo.toml @@ -17,7 +17,9 @@ bip39 = "2.0.0" boltz-client = { git = "https://github.com/dangeross/boltz-rust", branch = "savage-breez-latest" } chrono = "0.4" env_logger = "0.11" -flutter_rust_bridge = { version = "=2.2.0", features = ["chrono"], optional = true } +flutter_rust_bridge = { version = "=2.2.0", features = [ + "chrono", +], optional = true } log = { workspace = true } lwk_common = "0.7.0" lwk_signer = "0.7.0" @@ -36,7 +38,10 @@ openssl = { version = "0.10", features = ["vendored"] } tokio = { version = "1", features = ["rt", "macros"] } tokio-stream = { version = "0.1.14", features = ["sync"] } url = "2.5.0" -futures-util = { version = "0.3.28", default-features = false, features = ["sink", "std"] } +futures-util = { version = "0.3.28", default-features = false, features = [ + "sink", + "std", +] } async-trait = "0.1.80" hex = "0.4" reqwest = { version = "=0.11.20", features = ["json"] } diff --git a/lib/core/src/bindings.rs b/lib/core/src/bindings.rs index 74f1a75..76eabdd 100644 --- a/lib/core/src/bindings.rs +++ b/lib/core/src/bindings.rs @@ -101,15 +101,15 @@ impl BindingLiquidSdk { pub async fn send_payment( &self, - req: PrepareSendResponse, + req: SendPaymentRequest, ) -> Result { self.sdk.send_payment(&req).await } pub async fn prepare_receive_payment( &self, - req: PrepareReceivePaymentRequest, - ) -> Result { + req: PrepareReceiveRequest, + ) -> Result { self.sdk.prepare_receive_payment(&req).await } @@ -144,20 +144,6 @@ impl BindingLiquidSdk { self.sdk.pay_onchain(&req).await } - pub async fn prepare_receive_onchain( - &self, - req: PrepareReceiveOnchainRequest, - ) -> Result { - self.sdk.prepare_receive_onchain(&req).await - } - - pub async fn receive_onchain( - &self, - req: PrepareReceiveOnchainResponse, - ) -> Result { - self.sdk.receive_onchain(&req).await - } - pub async fn prepare_buy_bitcoin( &self, req: PrepareBuyBitcoinRequest, diff --git a/lib/core/src/chain_swap.rs b/lib/core/src/chain_swap.rs index b8da2e3..27d885f 100644 --- a/lib/core/src/chain_swap.rs +++ b/lib/core/src/chain_swap.rs @@ -399,7 +399,7 @@ impl ChainSwapStateHandler { fees_sat: lockup_tx_fees_sat + swap.claim_fees_sat, payment_type: PaymentType::Send, is_confirmed: false, - })?; + }, None)?; self.update_swap_info(id, Pending, None, Some(&lockup_tx_id), None, None) .await?; @@ -633,14 +633,17 @@ impl ChainSwapStateHandler { if chain_swap.direction == Direction::Incoming { // We insert a pseudo-claim-tx in case LWK fails to pick up the new mempool tx for a while // This makes the tx known to the SDK (get_info, list_payments) instantly - self.persister.insert_or_update_payment(PaymentTxData { - tx_id: claim_tx_id.clone(), - timestamp: Some(utils::now()), - amount_sat: chain_swap.receiver_amount_sat, - fees_sat: 0, - payment_type: PaymentType::Receive, - is_confirmed: false, - })?; + self.persister.insert_or_update_payment( + PaymentTxData { + tx_id: claim_tx_id.clone(), + timestamp: Some(utils::now()), + amount_sat: chain_swap.receiver_amount_sat, + fees_sat: 0, + payment_type: PaymentType::Receive, + is_confirmed: false, + }, + None, + )?; } self.update_swap_info( diff --git a/lib/core/src/error.rs b/lib/core/src/error.rs index 6aab310..70371ba 100644 --- a/lib/core/src/error.rs +++ b/lib/core/src/error.rs @@ -70,6 +70,12 @@ pub enum PaymentError { #[error("Amount is out of range")] AmountOutOfRange, + #[error("Amount is missing: {err}")] + AmountMissing { err: String }, + + #[error("Invalid network: {err}")] + InvalidNetwork { err: String }, + #[error("Generic error: {err}")] Generic { err: String }, diff --git a/lib/core/src/frb_generated.io.rs b/lib/core/src/frb_generated.io.rs index 2cec4ab..e2c717b 100644 --- a/lib/core/src/frb_generated.io.rs +++ b/lib/core/src/frb_generated.io.rs @@ -204,6 +204,13 @@ impl CstDecode for *mut i64 { unsafe { *flutter_rust_bridge::for_generated::box_from_leak_ptr(self) } } } +impl CstDecode for *mut wire_cst_liquid_address_data { + // Codec=Cst (C-struct based), see doc to use other codecs + fn cst_decode(self) -> crate::bindings::LiquidAddressData { + let wrap = unsafe { flutter_rust_bridge::for_generated::box_from_leak_ptr(self) }; + CstDecode::::cst_decode(*wrap).into() + } +} impl CstDecode for *mut wire_cst_list_payments_request { // Codec=Cst (C-struct based), see doc to use other codecs fn cst_decode(self) -> crate::model::ListPaymentsRequest { @@ -308,6 +315,13 @@ impl CstDecode for *mut wire_cst_payment { CstDecode::::cst_decode(*wrap).into() } } +impl CstDecode for *mut wire_cst_payment_details { + // Codec=Cst (C-struct based), see doc to use other codecs + fn cst_decode(self) -> crate::model::PaymentDetails { + let wrap = unsafe { flutter_rust_bridge::for_generated::box_from_leak_ptr(self) }; + CstDecode::::cst_decode(*wrap).into() + } +} impl CstDecode for *mut wire_cst_prepare_buy_bitcoin_request { @@ -326,31 +340,11 @@ impl CstDecode CstDecode::::cst_decode(*wrap).into() } } -impl CstDecode - for *mut wire_cst_prepare_receive_onchain_request -{ +impl CstDecode for *mut wire_cst_prepare_receive_request { // Codec=Cst (C-struct based), see doc to use other codecs - fn cst_decode(self) -> crate::model::PrepareReceiveOnchainRequest { + fn cst_decode(self) -> crate::model::PrepareReceiveRequest { let wrap = unsafe { flutter_rust_bridge::for_generated::box_from_leak_ptr(self) }; - CstDecode::::cst_decode(*wrap).into() - } -} -impl CstDecode - for *mut wire_cst_prepare_receive_onchain_response -{ - // Codec=Cst (C-struct based), see doc to use other codecs - fn cst_decode(self) -> crate::model::PrepareReceiveOnchainResponse { - let wrap = unsafe { flutter_rust_bridge::for_generated::box_from_leak_ptr(self) }; - CstDecode::::cst_decode(*wrap).into() - } -} -impl CstDecode - for *mut wire_cst_prepare_receive_payment_request -{ - // Codec=Cst (C-struct based), see doc to use other codecs - fn cst_decode(self) -> crate::model::PrepareReceivePaymentRequest { - let wrap = unsafe { flutter_rust_bridge::for_generated::box_from_leak_ptr(self) }; - CstDecode::::cst_decode(*wrap).into() + CstDecode::::cst_decode(*wrap).into() } } impl CstDecode for *mut wire_cst_prepare_refund_request { @@ -367,13 +361,6 @@ impl CstDecode for *mut wire_cst_prepare_send_ CstDecode::::cst_decode(*wrap).into() } } -impl CstDecode for *mut wire_cst_prepare_send_response { - // Codec=Cst (C-struct based), see doc to use other codecs - fn cst_decode(self) -> crate::model::PrepareSendResponse { - let wrap = unsafe { flutter_rust_bridge::for_generated::box_from_leak_ptr(self) }; - CstDecode::::cst_decode(*wrap).into() - } -} impl CstDecode for *mut wire_cst_receive_payment_request { // Codec=Cst (C-struct based), see doc to use other codecs fn cst_decode(self) -> crate::model::ReceivePaymentRequest { @@ -402,6 +389,13 @@ impl CstDecode for *mut wire_cst_sdk_event { CstDecode::::cst_decode(*wrap).into() } } +impl CstDecode for *mut wire_cst_send_payment_request { + // Codec=Cst (C-struct based), see doc to use other codecs + fn cst_decode(self) -> crate::model::SendPaymentRequest { + let wrap = unsafe { flutter_rust_bridge::for_generated::box_from_leak_ptr(self) }; + CstDecode::::cst_decode(*wrap).into() + } +} impl CstDecode for *mut wire_cst_success_action_processed { // Codec=Cst (C-struct based), see doc to use other codecs fn cst_decode(self) -> crate::bindings::SuccessActionProcessed { @@ -439,7 +433,7 @@ impl CstDecode for wire_cst_buy_bitcoin_request // Codec=Cst (C-struct based), see doc to use other codecs fn cst_decode(self) -> crate::model::BuyBitcoinRequest { crate::model::BuyBitcoinRequest { - prepare_res: self.prepare_res.cst_decode(), + prepare_response: self.prepare_response.cst_decode(), redirect_url: self.redirect_url.cst_decode(), } } @@ -513,42 +507,48 @@ impl CstDecode for wire_cst_input_type { } } 1 => { + let ans = unsafe { self.kind.LiquidAddress }; + crate::bindings::InputType::LiquidAddress { + address: ans.address.cst_decode(), + } + } + 2 => { let ans = unsafe { self.kind.Bolt11 }; crate::bindings::InputType::Bolt11 { invoice: ans.invoice.cst_decode(), } } - 2 => { + 3 => { let ans = unsafe { self.kind.NodeId }; crate::bindings::InputType::NodeId { node_id: ans.node_id.cst_decode(), } } - 3 => { + 4 => { let ans = unsafe { self.kind.Url }; crate::bindings::InputType::Url { url: ans.url.cst_decode(), } } - 4 => { + 5 => { let ans = unsafe { self.kind.LnUrlPay }; crate::bindings::InputType::LnUrlPay { data: ans.data.cst_decode(), } } - 5 => { + 6 => { let ans = unsafe { self.kind.LnUrlWithdraw }; crate::bindings::InputType::LnUrlWithdraw { data: ans.data.cst_decode(), } } - 6 => { + 7 => { let ans = unsafe { self.kind.LnUrlAuth }; crate::bindings::InputType::LnUrlAuth { data: ans.data.cst_decode(), } } - 7 => { + 8 => { let ans = unsafe { self.kind.LnUrlError }; crate::bindings::InputType::LnUrlError { data: ans.data.cst_decode(), @@ -579,6 +579,19 @@ impl CstDecode for wire_cst_limits { } } } +impl CstDecode for wire_cst_liquid_address_data { + // Codec=Cst (C-struct based), see doc to use other codecs + fn cst_decode(self) -> crate::bindings::LiquidAddressData { + crate::bindings::LiquidAddressData { + address: self.address.cst_decode(), + network: self.network.cst_decode(), + asset_id: self.asset_id.cst_decode(), + amount_sat: self.amount_sat.cst_decode(), + label: self.label.cst_decode(), + message: self.message.cst_decode(), + } + } +} impl CstDecode> for *mut wire_cst_list_fiat_currency { // Codec=Cst (C-struct based), see doc to use other codecs fn cst_decode(self) -> Vec { @@ -1076,7 +1089,7 @@ impl CstDecode for wire_cst_pay_onchain_request fn cst_decode(self) -> crate::model::PayOnchainRequest { crate::model::PayOnchainRequest { address: self.address.cst_decode(), - prepare_res: self.prepare_res.cst_decode(), + prepare_response: self.prepare_response.cst_decode(), } } } @@ -1084,18 +1097,47 @@ impl CstDecode for wire_cst_payment { // Codec=Cst (C-struct based), see doc to use other codecs fn cst_decode(self) -> crate::model::Payment { crate::model::Payment { + destination: self.destination.cst_decode(), tx_id: self.tx_id.cst_decode(), - swap_id: self.swap_id.cst_decode(), timestamp: self.timestamp.cst_decode(), amount_sat: self.amount_sat.cst_decode(), fees_sat: self.fees_sat.cst_decode(), - preimage: self.preimage.cst_decode(), - bolt11: self.bolt11.cst_decode(), description: self.description.cst_decode(), - refund_tx_id: self.refund_tx_id.cst_decode(), - refund_tx_amount_sat: self.refund_tx_amount_sat.cst_decode(), payment_type: self.payment_type.cst_decode(), status: self.status.cst_decode(), + details: self.details.cst_decode(), + } + } +} +impl CstDecode for wire_cst_payment_details { + // Codec=Cst (C-struct based), see doc to use other codecs + fn cst_decode(self) -> crate::model::PaymentDetails { + match self.tag { + 0 => { + let ans = unsafe { self.kind.Lightning }; + crate::model::PaymentDetails::Lightning { + swap_id: ans.swap_id.cst_decode(), + preimage: ans.preimage.cst_decode(), + bolt11: ans.bolt11.cst_decode(), + refund_tx_id: ans.refund_tx_id.cst_decode(), + refund_tx_amount_sat: ans.refund_tx_amount_sat.cst_decode(), + } + } + 1 => { + let ans = unsafe { self.kind.Liquid }; + crate::model::PaymentDetails::Liquid { + address: ans.address.cst_decode(), + } + } + 2 => { + let ans = unsafe { self.kind.Bitcoin }; + crate::model::PaymentDetails::Bitcoin { + swap_id: ans.swap_id.cst_decode(), + refund_tx_id: ans.refund_tx_id.cst_decode(), + refund_tx_amount_sat: ans.refund_tx_amount_sat.cst_decode(), + } + } + _ => unreachable!(), } } } @@ -1108,50 +1150,62 @@ impl CstDecode for wire_cst_payment_error { 2 => crate::error::PaymentError::PaymentInProgress, 3 => crate::error::PaymentError::AmountOutOfRange, 4 => { + let ans = unsafe { self.kind.AmountMissing }; + crate::error::PaymentError::AmountMissing { + err: ans.err.cst_decode(), + } + } + 5 => { + let ans = unsafe { self.kind.NetworkMismatch }; + crate::error::PaymentError::NetworkMismatch { + err: ans.err.cst_decode(), + } + } + 6 => { let ans = unsafe { self.kind.Generic }; crate::error::PaymentError::Generic { err: ans.err.cst_decode(), } } - 5 => crate::error::PaymentError::InvalidOrExpiredFees, - 6 => crate::error::PaymentError::InsufficientFunds, - 7 => { + 7 => crate::error::PaymentError::InvalidOrExpiredFees, + 8 => crate::error::PaymentError::InsufficientFunds, + 9 => { let ans = unsafe { self.kind.InvalidInvoice }; crate::error::PaymentError::InvalidInvoice { err: ans.err.cst_decode(), } } - 8 => crate::error::PaymentError::InvalidPreimage, - 9 => { + 10 => crate::error::PaymentError::InvalidPreimage, + 11 => { let ans = unsafe { self.kind.LwkError }; crate::error::PaymentError::LwkError { err: ans.err.cst_decode(), } } - 10 => crate::error::PaymentError::PairsNotFound, - 11 => crate::error::PaymentError::PaymentTimeout, - 12 => crate::error::PaymentError::PersistError, - 13 => { + 12 => crate::error::PaymentError::PairsNotFound, + 13 => crate::error::PaymentError::PaymentTimeout, + 14 => crate::error::PaymentError::PersistError, + 15 => { let ans = unsafe { self.kind.ReceiveError }; crate::error::PaymentError::ReceiveError { err: ans.err.cst_decode(), } } - 14 => { + 16 => { let ans = unsafe { self.kind.Refunded }; crate::error::PaymentError::Refunded { err: ans.err.cst_decode(), refund_tx_id: ans.refund_tx_id.cst_decode(), } } - 15 => crate::error::PaymentError::SelfTransferNotSupported, - 16 => { + 17 => crate::error::PaymentError::SelfTransferNotSupported, + 18 => { let ans = unsafe { self.kind.SendError }; crate::error::PaymentError::SendError { err: ans.err.cst_decode(), } } - 17 => { + 19 => { let ans = unsafe { self.kind.SignerError }; crate::error::PaymentError::SignerError { err: ans.err.cst_decode(), @@ -1199,44 +1253,21 @@ impl CstDecode for wire_cst_prepare_pay } } } -impl CstDecode - for wire_cst_prepare_receive_onchain_request -{ +impl CstDecode for wire_cst_prepare_receive_request { // Codec=Cst (C-struct based), see doc to use other codecs - fn cst_decode(self) -> crate::model::PrepareReceiveOnchainRequest { - crate::model::PrepareReceiveOnchainRequest { - payer_amount_sat: self.payer_amount_sat.cst_decode(), + fn cst_decode(self) -> crate::model::PrepareReceiveRequest { + crate::model::PrepareReceiveRequest { + amount_sat: self.amount_sat.cst_decode(), + payment_method: self.payment_method.cst_decode(), } } } -impl CstDecode - for wire_cst_prepare_receive_onchain_response -{ +impl CstDecode for wire_cst_prepare_receive_response { // Codec=Cst (C-struct based), see doc to use other codecs - fn cst_decode(self) -> crate::model::PrepareReceiveOnchainResponse { - crate::model::PrepareReceiveOnchainResponse { - payer_amount_sat: self.payer_amount_sat.cst_decode(), - fees_sat: self.fees_sat.cst_decode(), - } - } -} -impl CstDecode - for wire_cst_prepare_receive_payment_request -{ - // Codec=Cst (C-struct based), see doc to use other codecs - fn cst_decode(self) -> crate::model::PrepareReceivePaymentRequest { - crate::model::PrepareReceivePaymentRequest { - payer_amount_sat: self.payer_amount_sat.cst_decode(), - } - } -} -impl CstDecode - for wire_cst_prepare_receive_payment_response -{ - // Codec=Cst (C-struct based), see doc to use other codecs - fn cst_decode(self) -> crate::model::PrepareReceivePaymentResponse { - crate::model::PrepareReceivePaymentResponse { - payer_amount_sat: self.payer_amount_sat.cst_decode(), + fn cst_decode(self) -> crate::model::PrepareReceiveResponse { + crate::model::PrepareReceiveResponse { + payment_method: self.payment_method.cst_decode(), + amount_sat: self.amount_sat.cst_decode(), fees_sat: self.fees_sat.cst_decode(), } } @@ -1265,7 +1296,8 @@ impl CstDecode for wire_cst_prepare_send_reque // Codec=Cst (C-struct based), see doc to use other codecs fn cst_decode(self) -> crate::model::PrepareSendRequest { crate::model::PrepareSendRequest { - invoice: self.invoice.cst_decode(), + destination: self.destination.cst_decode(), + amount_sat: self.amount_sat.cst_decode(), } } } @@ -1273,7 +1305,7 @@ impl CstDecode for wire_cst_prepare_send_resp // Codec=Cst (C-struct based), see doc to use other codecs fn cst_decode(self) -> crate::model::PrepareSendResponse { crate::model::PrepareSendResponse { - invoice: self.invoice.cst_decode(), + destination: self.destination.cst_decode(), fees_sat: self.fees_sat.cst_decode(), } } @@ -1287,21 +1319,12 @@ impl CstDecode for wire_cst_rate { } } } -impl CstDecode for wire_cst_receive_onchain_response { - // Codec=Cst (C-struct based), see doc to use other codecs - fn cst_decode(self) -> crate::model::ReceiveOnchainResponse { - crate::model::ReceiveOnchainResponse { - address: self.address.cst_decode(), - bip21: self.bip21.cst_decode(), - } - } -} impl CstDecode for wire_cst_receive_payment_request { // Codec=Cst (C-struct based), see doc to use other codecs fn cst_decode(self) -> crate::model::ReceivePaymentRequest { crate::model::ReceivePaymentRequest { description: self.description.cst_decode(), - prepare_res: self.prepare_res.cst_decode(), + prepare_response: self.prepare_response.cst_decode(), } } } @@ -1309,8 +1332,7 @@ impl CstDecode for wire_cst_receive_paymen // Codec=Cst (C-struct based), see doc to use other codecs fn cst_decode(self) -> crate::model::ReceivePaymentResponse { crate::model::ReceivePaymentResponse { - id: self.id.cst_decode(), - invoice: self.invoice.cst_decode(), + destination: self.destination.cst_decode(), } } } @@ -1451,6 +1473,34 @@ impl CstDecode for wire_cst_sdk_event { } } } +impl CstDecode for wire_cst_send_destination { + // Codec=Cst (C-struct based), see doc to use other codecs + fn cst_decode(self) -> crate::model::SendDestination { + match self.tag { + 0 => { + let ans = unsafe { self.kind.LiquidAddress }; + crate::model::SendDestination::LiquidAddress { + address_data: ans.address_data.cst_decode(), + } + } + 1 => { + let ans = unsafe { self.kind.Bolt11 }; + crate::model::SendDestination::Bolt11 { + invoice: ans.invoice.cst_decode(), + } + } + _ => unreachable!(), + } + } +} +impl CstDecode for wire_cst_send_payment_request { + // Codec=Cst (C-struct based), see doc to use other codecs + fn cst_decode(self) -> crate::model::SendPaymentRequest { + crate::model::SendPaymentRequest { + prepare_response: self.prepare_response.cst_decode(), + } + } +} impl CstDecode for wire_cst_send_payment_response { // Codec=Cst (C-struct based), see doc to use other codecs fn cst_decode(self) -> crate::model::SendPaymentResponse { @@ -1575,7 +1625,7 @@ impl Default for wire_cst_bitcoin_address_data { impl NewWithNullPtr for wire_cst_buy_bitcoin_request { fn new_with_null_ptr() -> Self { Self { - prepare_res: Default::default(), + prepare_response: Default::default(), redirect_url: core::ptr::null_mut(), } } @@ -1703,6 +1753,23 @@ impl Default for wire_cst_limits { Self::new_with_null_ptr() } } +impl NewWithNullPtr for wire_cst_liquid_address_data { + fn new_with_null_ptr() -> Self { + Self { + address: core::ptr::null_mut(), + network: Default::default(), + asset_id: core::ptr::null_mut(), + amount_sat: core::ptr::null_mut(), + label: core::ptr::null_mut(), + message: core::ptr::null_mut(), + } + } +} +impl Default for wire_cst_liquid_address_data { + fn default() -> Self { + Self::new_with_null_ptr() + } +} impl NewWithNullPtr for wire_cst_list_payments_request { fn new_with_null_ptr() -> Self { Self { @@ -2020,7 +2087,7 @@ impl NewWithNullPtr for wire_cst_pay_onchain_request { fn new_with_null_ptr() -> Self { Self { address: core::ptr::null_mut(), - prepare_res: Default::default(), + prepare_response: Default::default(), } } } @@ -2032,18 +2099,15 @@ impl Default for wire_cst_pay_onchain_request { impl NewWithNullPtr for wire_cst_payment { fn new_with_null_ptr() -> Self { Self { + destination: core::ptr::null_mut(), tx_id: core::ptr::null_mut(), - swap_id: core::ptr::null_mut(), timestamp: Default::default(), amount_sat: Default::default(), fees_sat: Default::default(), - preimage: core::ptr::null_mut(), - bolt11: core::ptr::null_mut(), description: core::ptr::null_mut(), - refund_tx_id: core::ptr::null_mut(), - refund_tx_amount_sat: core::ptr::null_mut(), payment_type: Default::default(), status: Default::default(), + details: core::ptr::null_mut(), } } } @@ -2052,6 +2116,19 @@ impl Default for wire_cst_payment { Self::new_with_null_ptr() } } +impl NewWithNullPtr for wire_cst_payment_details { + fn new_with_null_ptr() -> Self { + Self { + tag: -1, + kind: PaymentDetailsKind { nil__: () }, + } + } +} +impl Default for wire_cst_payment_details { + fn default() -> Self { + Self::new_with_null_ptr() + } +} impl NewWithNullPtr for wire_cst_payment_error { fn new_with_null_ptr() -> Self { Self { @@ -2119,52 +2196,29 @@ impl Default for wire_cst_prepare_pay_onchain_response { Self::new_with_null_ptr() } } -impl NewWithNullPtr for wire_cst_prepare_receive_onchain_request { +impl NewWithNullPtr for wire_cst_prepare_receive_request { fn new_with_null_ptr() -> Self { Self { - payer_amount_sat: Default::default(), + amount_sat: core::ptr::null_mut(), + payment_method: Default::default(), } } } -impl Default for wire_cst_prepare_receive_onchain_request { +impl Default for wire_cst_prepare_receive_request { fn default() -> Self { Self::new_with_null_ptr() } } -impl NewWithNullPtr for wire_cst_prepare_receive_onchain_response { +impl NewWithNullPtr for wire_cst_prepare_receive_response { fn new_with_null_ptr() -> Self { Self { - payer_amount_sat: Default::default(), + payment_method: Default::default(), + amount_sat: core::ptr::null_mut(), fees_sat: Default::default(), } } } -impl Default for wire_cst_prepare_receive_onchain_response { - fn default() -> Self { - Self::new_with_null_ptr() - } -} -impl NewWithNullPtr for wire_cst_prepare_receive_payment_request { - fn new_with_null_ptr() -> Self { - Self { - payer_amount_sat: Default::default(), - } - } -} -impl Default for wire_cst_prepare_receive_payment_request { - fn default() -> Self { - Self::new_with_null_ptr() - } -} -impl NewWithNullPtr for wire_cst_prepare_receive_payment_response { - fn new_with_null_ptr() -> Self { - Self { - payer_amount_sat: Default::default(), - fees_sat: Default::default(), - } - } -} -impl Default for wire_cst_prepare_receive_payment_response { +impl Default for wire_cst_prepare_receive_response { fn default() -> Self { Self::new_with_null_ptr() } @@ -2200,7 +2254,8 @@ impl Default for wire_cst_prepare_refund_response { impl NewWithNullPtr for wire_cst_prepare_send_request { fn new_with_null_ptr() -> Self { Self { - invoice: core::ptr::null_mut(), + destination: core::ptr::null_mut(), + amount_sat: core::ptr::null_mut(), } } } @@ -2212,7 +2267,7 @@ impl Default for wire_cst_prepare_send_request { impl NewWithNullPtr for wire_cst_prepare_send_response { fn new_with_null_ptr() -> Self { Self { - invoice: core::ptr::null_mut(), + destination: Default::default(), fees_sat: Default::default(), } } @@ -2235,24 +2290,11 @@ impl Default for wire_cst_rate { Self::new_with_null_ptr() } } -impl NewWithNullPtr for wire_cst_receive_onchain_response { - fn new_with_null_ptr() -> Self { - Self { - address: core::ptr::null_mut(), - bip21: core::ptr::null_mut(), - } - } -} -impl Default for wire_cst_receive_onchain_response { - fn default() -> Self { - Self::new_with_null_ptr() - } -} impl NewWithNullPtr for wire_cst_receive_payment_request { fn new_with_null_ptr() -> Self { Self { description: core::ptr::null_mut(), - prepare_res: Default::default(), + prepare_response: Default::default(), } } } @@ -2264,8 +2306,7 @@ impl Default for wire_cst_receive_payment_request { impl NewWithNullPtr for wire_cst_receive_payment_response { fn new_with_null_ptr() -> Self { Self { - id: core::ptr::null_mut(), - invoice: core::ptr::null_mut(), + destination: core::ptr::null_mut(), } } } @@ -2398,6 +2439,31 @@ impl Default for wire_cst_sdk_event { Self::new_with_null_ptr() } } +impl NewWithNullPtr for wire_cst_send_destination { + fn new_with_null_ptr() -> Self { + Self { + tag: -1, + kind: SendDestinationKind { nil__: () }, + } + } +} +impl Default for wire_cst_send_destination { + fn default() -> Self { + Self::new_with_null_ptr() + } +} +impl NewWithNullPtr for wire_cst_send_payment_request { + fn new_with_null_ptr() -> Self { + Self { + prepare_response: Default::default(), + } + } +} +impl Default for wire_cst_send_payment_request { + fn default() -> Self { + Self::new_with_null_ptr() + } +} impl NewWithNullPtr for wire_cst_send_payment_response { fn new_with_null_ptr() -> Self { Self { @@ -2605,20 +2671,11 @@ pub extern "C" fn frbgen_breez_liquid_wire__crate__bindings__BindingLiquidSdk_pr wire__crate__bindings__BindingLiquidSdk_prepare_pay_onchain_impl(port_, that, req) } -#[no_mangle] -pub extern "C" fn frbgen_breez_liquid_wire__crate__bindings__BindingLiquidSdk_prepare_receive_onchain( - port_: i64, - that: usize, - req: *mut wire_cst_prepare_receive_onchain_request, -) { - wire__crate__bindings__BindingLiquidSdk_prepare_receive_onchain_impl(port_, that, req) -} - #[no_mangle] pub extern "C" fn frbgen_breez_liquid_wire__crate__bindings__BindingLiquidSdk_prepare_receive_payment( port_: i64, that: usize, - req: *mut wire_cst_prepare_receive_payment_request, + req: *mut wire_cst_prepare_receive_request, ) { wire__crate__bindings__BindingLiquidSdk_prepare_receive_payment_impl(port_, that, req) } @@ -2641,15 +2698,6 @@ pub extern "C" fn frbgen_breez_liquid_wire__crate__bindings__BindingLiquidSdk_pr wire__crate__bindings__BindingLiquidSdk_prepare_send_payment_impl(port_, that, req) } -#[no_mangle] -pub extern "C" fn frbgen_breez_liquid_wire__crate__bindings__BindingLiquidSdk_receive_onchain( - port_: i64, - that: usize, - req: *mut wire_cst_prepare_receive_onchain_response, -) { - wire__crate__bindings__BindingLiquidSdk_receive_onchain_impl(port_, that, req) -} - #[no_mangle] pub extern "C" fn frbgen_breez_liquid_wire__crate__bindings__BindingLiquidSdk_receive_payment( port_: i64, @@ -2696,7 +2744,7 @@ pub extern "C" fn frbgen_breez_liquid_wire__crate__bindings__BindingLiquidSdk_re pub extern "C" fn frbgen_breez_liquid_wire__crate__bindings__BindingLiquidSdk_send_payment( port_: i64, that: usize, - req: *mut wire_cst_prepare_send_response, + req: *mut wire_cst_send_payment_request, ) { wire__crate__bindings__BindingLiquidSdk_send_payment_impl(port_, that, req) } @@ -2840,6 +2888,14 @@ pub extern "C" fn frbgen_breez_liquid_cst_new_box_autoadd_i_64(value: i64) -> *m flutter_rust_bridge::for_generated::new_leak_box_ptr(value) } +#[no_mangle] +pub extern "C" fn frbgen_breez_liquid_cst_new_box_autoadd_liquid_address_data( +) -> *mut wire_cst_liquid_address_data { + flutter_rust_bridge::for_generated::new_leak_box_ptr( + wire_cst_liquid_address_data::new_with_null_ptr(), + ) +} + #[no_mangle] pub extern "C" fn frbgen_breez_liquid_cst_new_box_autoadd_list_payments_request( ) -> *mut wire_cst_list_payments_request { @@ -2946,6 +3002,14 @@ pub extern "C" fn frbgen_breez_liquid_cst_new_box_autoadd_payment() -> *mut wire flutter_rust_bridge::for_generated::new_leak_box_ptr(wire_cst_payment::new_with_null_ptr()) } +#[no_mangle] +pub extern "C" fn frbgen_breez_liquid_cst_new_box_autoadd_payment_details( +) -> *mut wire_cst_payment_details { + flutter_rust_bridge::for_generated::new_leak_box_ptr( + wire_cst_payment_details::new_with_null_ptr(), + ) +} + #[no_mangle] pub extern "C" fn frbgen_breez_liquid_cst_new_box_autoadd_prepare_buy_bitcoin_request( ) -> *mut wire_cst_prepare_buy_bitcoin_request { @@ -2963,26 +3027,10 @@ pub extern "C" fn frbgen_breez_liquid_cst_new_box_autoadd_prepare_pay_onchain_re } #[no_mangle] -pub extern "C" fn frbgen_breez_liquid_cst_new_box_autoadd_prepare_receive_onchain_request( -) -> *mut wire_cst_prepare_receive_onchain_request { +pub extern "C" fn frbgen_breez_liquid_cst_new_box_autoadd_prepare_receive_request( +) -> *mut wire_cst_prepare_receive_request { flutter_rust_bridge::for_generated::new_leak_box_ptr( - wire_cst_prepare_receive_onchain_request::new_with_null_ptr(), - ) -} - -#[no_mangle] -pub extern "C" fn frbgen_breez_liquid_cst_new_box_autoadd_prepare_receive_onchain_response( -) -> *mut wire_cst_prepare_receive_onchain_response { - flutter_rust_bridge::for_generated::new_leak_box_ptr( - wire_cst_prepare_receive_onchain_response::new_with_null_ptr(), - ) -} - -#[no_mangle] -pub extern "C" fn frbgen_breez_liquid_cst_new_box_autoadd_prepare_receive_payment_request( -) -> *mut wire_cst_prepare_receive_payment_request { - flutter_rust_bridge::for_generated::new_leak_box_ptr( - wire_cst_prepare_receive_payment_request::new_with_null_ptr(), + wire_cst_prepare_receive_request::new_with_null_ptr(), ) } @@ -3002,14 +3050,6 @@ pub extern "C" fn frbgen_breez_liquid_cst_new_box_autoadd_prepare_send_request( ) } -#[no_mangle] -pub extern "C" fn frbgen_breez_liquid_cst_new_box_autoadd_prepare_send_response( -) -> *mut wire_cst_prepare_send_response { - flutter_rust_bridge::for_generated::new_leak_box_ptr( - wire_cst_prepare_send_response::new_with_null_ptr(), - ) -} - #[no_mangle] pub extern "C" fn frbgen_breez_liquid_cst_new_box_autoadd_receive_payment_request( ) -> *mut wire_cst_receive_payment_request { @@ -3039,6 +3079,14 @@ pub extern "C" fn frbgen_breez_liquid_cst_new_box_autoadd_sdk_event() -> *mut wi flutter_rust_bridge::for_generated::new_leak_box_ptr(wire_cst_sdk_event::new_with_null_ptr()) } +#[no_mangle] +pub extern "C" fn frbgen_breez_liquid_cst_new_box_autoadd_send_payment_request( +) -> *mut wire_cst_send_payment_request { + flutter_rust_bridge::for_generated::new_leak_box_ptr( + wire_cst_send_payment_request::new_with_null_ptr(), + ) +} + #[no_mangle] pub extern "C" fn frbgen_breez_liquid_cst_new_box_autoadd_success_action_processed( ) -> *mut wire_cst_success_action_processed { @@ -3251,7 +3299,7 @@ pub struct wire_cst_bitcoin_address_data { #[repr(C)] #[derive(Clone, Copy)] pub struct wire_cst_buy_bitcoin_request { - prepare_res: wire_cst_prepare_buy_bitcoin_response, + prepare_response: wire_cst_prepare_buy_bitcoin_response, redirect_url: *mut wire_cst_list_prim_u_8_strict, } #[repr(C)] @@ -3307,6 +3355,7 @@ pub struct wire_cst_input_type { #[derive(Clone, Copy)] pub union InputTypeKind { BitcoinAddress: wire_cst_InputType_BitcoinAddress, + LiquidAddress: wire_cst_InputType_LiquidAddress, Bolt11: wire_cst_InputType_Bolt11, NodeId: wire_cst_InputType_NodeId, Url: wire_cst_InputType_Url, @@ -3323,6 +3372,11 @@ pub struct wire_cst_InputType_BitcoinAddress { } #[repr(C)] #[derive(Clone, Copy)] +pub struct wire_cst_InputType_LiquidAddress { + address: *mut wire_cst_liquid_address_data, +} +#[repr(C)] +#[derive(Clone, Copy)] pub struct wire_cst_InputType_Bolt11 { invoice: *mut wire_cst_ln_invoice, } @@ -3371,6 +3425,16 @@ pub struct wire_cst_limits { } #[repr(C)] #[derive(Clone, Copy)] +pub struct wire_cst_liquid_address_data { + address: *mut wire_cst_list_prim_u_8_strict, + network: i32, + asset_id: *mut wire_cst_list_prim_u_8_strict, + amount_sat: *mut u64, + label: *mut wire_cst_list_prim_u_8_strict, + message: *mut wire_cst_list_prim_u_8_strict, +} +#[repr(C)] +#[derive(Clone, Copy)] pub struct wire_cst_list_fiat_currency { ptr: *mut wire_cst_fiat_currency, len: i32, @@ -3784,23 +3848,55 @@ pub struct wire_cst_onchain_payment_limits_response { #[derive(Clone, Copy)] pub struct wire_cst_pay_onchain_request { address: *mut wire_cst_list_prim_u_8_strict, - prepare_res: wire_cst_prepare_pay_onchain_response, + prepare_response: wire_cst_prepare_pay_onchain_response, } #[repr(C)] #[derive(Clone, Copy)] pub struct wire_cst_payment { + destination: *mut wire_cst_list_prim_u_8_strict, tx_id: *mut wire_cst_list_prim_u_8_strict, - swap_id: *mut wire_cst_list_prim_u_8_strict, timestamp: u32, amount_sat: u64, fees_sat: u64, - preimage: *mut wire_cst_list_prim_u_8_strict, - bolt11: *mut wire_cst_list_prim_u_8_strict, description: *mut wire_cst_list_prim_u_8_strict, - refund_tx_id: *mut wire_cst_list_prim_u_8_strict, - refund_tx_amount_sat: *mut u64, payment_type: i32, status: i32, + details: *mut wire_cst_payment_details, +} +#[repr(C)] +#[derive(Clone, Copy)] +pub struct wire_cst_payment_details { + tag: i32, + kind: PaymentDetailsKind, +} +#[repr(C)] +#[derive(Clone, Copy)] +pub union PaymentDetailsKind { + Lightning: wire_cst_PaymentDetails_Lightning, + Liquid: wire_cst_PaymentDetails_Liquid, + Bitcoin: wire_cst_PaymentDetails_Bitcoin, + nil__: (), +} +#[repr(C)] +#[derive(Clone, Copy)] +pub struct wire_cst_PaymentDetails_Lightning { + swap_id: *mut wire_cst_list_prim_u_8_strict, + preimage: *mut wire_cst_list_prim_u_8_strict, + bolt11: *mut wire_cst_list_prim_u_8_strict, + refund_tx_id: *mut wire_cst_list_prim_u_8_strict, + refund_tx_amount_sat: *mut u64, +} +#[repr(C)] +#[derive(Clone, Copy)] +pub struct wire_cst_PaymentDetails_Liquid { + address: *mut wire_cst_list_prim_u_8_strict, +} +#[repr(C)] +#[derive(Clone, Copy)] +pub struct wire_cst_PaymentDetails_Bitcoin { + swap_id: *mut wire_cst_list_prim_u_8_strict, + refund_tx_id: *mut wire_cst_list_prim_u_8_strict, + refund_tx_amount_sat: *mut u64, } #[repr(C)] #[derive(Clone, Copy)] @@ -3811,6 +3907,8 @@ pub struct wire_cst_payment_error { #[repr(C)] #[derive(Clone, Copy)] pub union PaymentErrorKind { + AmountMissing: wire_cst_PaymentError_AmountMissing, + NetworkMismatch: wire_cst_PaymentError_NetworkMismatch, Generic: wire_cst_PaymentError_Generic, InvalidInvoice: wire_cst_PaymentError_InvalidInvoice, LwkError: wire_cst_PaymentError_LwkError, @@ -3822,6 +3920,16 @@ pub union PaymentErrorKind { } #[repr(C)] #[derive(Clone, Copy)] +pub struct wire_cst_PaymentError_AmountMissing { + err: *mut wire_cst_list_prim_u_8_strict, +} +#[repr(C)] +#[derive(Clone, Copy)] +pub struct wire_cst_PaymentError_NetworkMismatch { + err: *mut wire_cst_list_prim_u_8_strict, +} +#[repr(C)] +#[derive(Clone, Copy)] pub struct wire_cst_PaymentError_Generic { err: *mut wire_cst_list_prim_u_8_strict, } @@ -3884,24 +3992,15 @@ pub struct wire_cst_prepare_pay_onchain_response { } #[repr(C)] #[derive(Clone, Copy)] -pub struct wire_cst_prepare_receive_onchain_request { - payer_amount_sat: u64, +pub struct wire_cst_prepare_receive_request { + amount_sat: *mut u64, + payment_method: i32, } #[repr(C)] #[derive(Clone, Copy)] -pub struct wire_cst_prepare_receive_onchain_response { - payer_amount_sat: u64, - fees_sat: u64, -} -#[repr(C)] -#[derive(Clone, Copy)] -pub struct wire_cst_prepare_receive_payment_request { - payer_amount_sat: u64, -} -#[repr(C)] -#[derive(Clone, Copy)] -pub struct wire_cst_prepare_receive_payment_response { - payer_amount_sat: u64, +pub struct wire_cst_prepare_receive_response { + payment_method: i32, + amount_sat: *mut u64, fees_sat: u64, } #[repr(C)] @@ -3921,12 +4020,13 @@ pub struct wire_cst_prepare_refund_response { #[repr(C)] #[derive(Clone, Copy)] pub struct wire_cst_prepare_send_request { - invoice: *mut wire_cst_list_prim_u_8_strict, + destination: *mut wire_cst_list_prim_u_8_strict, + amount_sat: *mut u64, } #[repr(C)] #[derive(Clone, Copy)] pub struct wire_cst_prepare_send_response { - invoice: *mut wire_cst_list_prim_u_8_strict, + destination: wire_cst_send_destination, fees_sat: u64, } #[repr(C)] @@ -3937,21 +4037,14 @@ pub struct wire_cst_rate { } #[repr(C)] #[derive(Clone, Copy)] -pub struct wire_cst_receive_onchain_response { - address: *mut wire_cst_list_prim_u_8_strict, - bip21: *mut wire_cst_list_prim_u_8_strict, -} -#[repr(C)] -#[derive(Clone, Copy)] pub struct wire_cst_receive_payment_request { description: *mut wire_cst_list_prim_u_8_strict, - prepare_res: wire_cst_prepare_receive_payment_response, + prepare_response: wire_cst_prepare_receive_response, } #[repr(C)] #[derive(Clone, Copy)] pub struct wire_cst_receive_payment_response { - id: *mut wire_cst_list_prim_u_8_strict, - invoice: *mut wire_cst_list_prim_u_8_strict, + destination: *mut wire_cst_list_prim_u_8_strict, } #[repr(C)] #[derive(Clone, Copy)] @@ -4074,6 +4167,34 @@ pub struct wire_cst_SdkEvent_PaymentWaitingConfirmation { } #[repr(C)] #[derive(Clone, Copy)] +pub struct wire_cst_send_destination { + tag: i32, + kind: SendDestinationKind, +} +#[repr(C)] +#[derive(Clone, Copy)] +pub union SendDestinationKind { + LiquidAddress: wire_cst_SendDestination_LiquidAddress, + Bolt11: wire_cst_SendDestination_Bolt11, + nil__: (), +} +#[repr(C)] +#[derive(Clone, Copy)] +pub struct wire_cst_SendDestination_LiquidAddress { + address_data: *mut wire_cst_liquid_address_data, +} +#[repr(C)] +#[derive(Clone, Copy)] +pub struct wire_cst_SendDestination_Bolt11 { + invoice: *mut wire_cst_ln_invoice, +} +#[repr(C)] +#[derive(Clone, Copy)] +pub struct wire_cst_send_payment_request { + prepare_response: wire_cst_prepare_send_response, +} +#[repr(C)] +#[derive(Clone, Copy)] pub struct wire_cst_send_payment_response { payment: wire_cst_payment, } diff --git a/lib/core/src/frb_generated.rs b/lib/core/src/frb_generated.rs index 40a098c..f57f907 100644 --- a/lib/core/src/frb_generated.rs +++ b/lib/core/src/frb_generated.rs @@ -39,7 +39,7 @@ flutter_rust_bridge::frb_generated_boilerplate!( default_rust_auto_opaque = RustAutoOpaqueNom, ); pub(crate) const FLUTTER_RUST_BRIDGE_CODEGEN_VERSION: &str = "2.2.0"; -pub(crate) const FLUTTER_RUST_BRIDGE_CODEGEN_CONTENT_HASH: i32 = -119028624; +pub(crate) const FLUTTER_RUST_BRIDGE_CODEGEN_CONTENT_HASH: i32 = -1074530283; // Section: executor @@ -876,61 +876,12 @@ fn wire__crate__bindings__BindingLiquidSdk_prepare_pay_onchain_impl( }, ) } -fn wire__crate__bindings__BindingLiquidSdk_prepare_receive_onchain_impl( - port_: flutter_rust_bridge::for_generated::MessagePort, - that: impl CstDecode< - RustOpaqueNom>, - >, - req: impl CstDecode, -) { - FLUTTER_RUST_BRIDGE_HANDLER.wrap_async::( - flutter_rust_bridge::for_generated::TaskInfo { - debug_name: "BindingLiquidSdk_prepare_receive_onchain", - port: Some(port_), - mode: flutter_rust_bridge::for_generated::FfiCallMode::Normal, - }, - move || { - let api_that = that.cst_decode(); - let api_req = req.cst_decode(); - move |context| async move { - transform_result_dco::<_, _, crate::error::PaymentError>( - (move || async move { - let mut api_that_guard = None; - let decode_indices_ = - flutter_rust_bridge::for_generated::lockable_compute_decode_order( - vec![flutter_rust_bridge::for_generated::LockableOrderInfo::new( - &api_that, 0, false, - )], - ); - for i in decode_indices_ { - match i { - 0 => { - api_that_guard = - Some(api_that.lockable_decode_async_ref().await) - } - _ => unreachable!(), - } - } - let api_that_guard = api_that_guard.unwrap(); - let output_ok = crate::bindings::BindingLiquidSdk::prepare_receive_onchain( - &*api_that_guard, - api_req, - ) - .await?; - Ok(output_ok) - })() - .await, - ) - } - }, - ) -} fn wire__crate__bindings__BindingLiquidSdk_prepare_receive_payment_impl( port_: flutter_rust_bridge::for_generated::MessagePort, that: impl CstDecode< RustOpaqueNom>, >, - req: impl CstDecode, + req: impl CstDecode, ) { FLUTTER_RUST_BRIDGE_HANDLER.wrap_async::( flutter_rust_bridge::for_generated::TaskInfo { @@ -1072,55 +1023,6 @@ fn wire__crate__bindings__BindingLiquidSdk_prepare_send_payment_impl( }, ) } -fn wire__crate__bindings__BindingLiquidSdk_receive_onchain_impl( - port_: flutter_rust_bridge::for_generated::MessagePort, - that: impl CstDecode< - RustOpaqueNom>, - >, - req: impl CstDecode, -) { - FLUTTER_RUST_BRIDGE_HANDLER.wrap_async::( - flutter_rust_bridge::for_generated::TaskInfo { - debug_name: "BindingLiquidSdk_receive_onchain", - port: Some(port_), - mode: flutter_rust_bridge::for_generated::FfiCallMode::Normal, - }, - move || { - let api_that = that.cst_decode(); - let api_req = req.cst_decode(); - move |context| async move { - transform_result_dco::<_, _, crate::error::PaymentError>( - (move || async move { - let mut api_that_guard = None; - let decode_indices_ = - flutter_rust_bridge::for_generated::lockable_compute_decode_order( - vec![flutter_rust_bridge::for_generated::LockableOrderInfo::new( - &api_that, 0, false, - )], - ); - for i in decode_indices_ { - match i { - 0 => { - api_that_guard = - Some(api_that.lockable_decode_async_ref().await) - } - _ => unreachable!(), - } - } - let api_that_guard = api_that_guard.unwrap(); - let output_ok = crate::bindings::BindingLiquidSdk::receive_onchain( - &*api_that_guard, - api_req, - ) - .await?; - Ok(output_ok) - })() - .await, - ) - } - }, - ) -} fn wire__crate__bindings__BindingLiquidSdk_receive_payment_impl( port_: flutter_rust_bridge::for_generated::MessagePort, that: impl CstDecode< @@ -1350,7 +1252,7 @@ fn wire__crate__bindings__BindingLiquidSdk_send_payment_impl( that: impl CstDecode< RustOpaqueNom>, >, - req: impl CstDecode, + req: impl CstDecode, ) { FLUTTER_RUST_BRIDGE_HANDLER.wrap_async::( flutter_rust_bridge::for_generated::TaskInfo { @@ -1832,6 +1734,17 @@ impl CstDecode for i32 { } } } +impl CstDecode for i32 { + // Codec=Cst (C-struct based), see doc to use other codecs + fn cst_decode(self) -> crate::model::PaymentMethod { + match self { + 0 => crate::model::PaymentMethod::Lightning, + 1 => crate::model::PaymentMethod::BitcoinAddress, + 2 => crate::model::PaymentMethod::LiquidAddress, + _ => unreachable!("Invalid variant for PaymentMethod: {}", self), + } + } +} impl CstDecode for i32 { // Codec=Cst (C-struct based), see doc to use other codecs fn cst_decode(self) -> crate::model::PaymentState { @@ -2038,11 +1951,11 @@ impl SseDecode for crate::model::BuyBitcoinProvider { impl SseDecode for crate::model::BuyBitcoinRequest { // Codec=Sse (Serialization based), see doc to use other codecs fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self { - let mut var_prepareRes = + let mut var_prepareResponse = ::sse_decode(deserializer); let mut var_redirectUrl = >::sse_decode(deserializer); return crate::model::BuyBitcoinRequest { - prepare_res: var_prepareRes, + prepare_response: var_prepareResponse, redirect_url: var_redirectUrl, }; } @@ -2900,6 +2813,17 @@ impl SseDecode for Option { } } +impl SseDecode for Option { + // Codec=Sse (Serialization based), see doc to use other codecs + fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self { + if (::sse_decode(deserializer)) { + return Some(::sse_decode(deserializer)); + } else { + return None; + } + } +} + impl SseDecode for Option { // Codec=Sse (Serialization based), see doc to use other codecs fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self { @@ -2961,11 +2885,11 @@ impl SseDecode for crate::model::PayOnchainRequest { // Codec=Sse (Serialization based), see doc to use other codecs fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self { let mut var_address = ::sse_decode(deserializer); - let mut var_prepareRes = + let mut var_prepareResponse = ::sse_decode(deserializer); return crate::model::PayOnchainRequest { address: var_address, - prepare_res: var_prepareRes, + prepare_response: var_prepareResponse, }; } } @@ -2973,35 +2897,75 @@ impl SseDecode for crate::model::PayOnchainRequest { impl SseDecode for crate::model::Payment { // Codec=Sse (Serialization based), see doc to use other codecs fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self { + let mut var_destination = >::sse_decode(deserializer); let mut var_txId = >::sse_decode(deserializer); - let mut var_swapId = >::sse_decode(deserializer); let mut var_timestamp = ::sse_decode(deserializer); let mut var_amountSat = ::sse_decode(deserializer); let mut var_feesSat = ::sse_decode(deserializer); - let mut var_preimage = >::sse_decode(deserializer); - let mut var_bolt11 = >::sse_decode(deserializer); - let mut var_description = ::sse_decode(deserializer); - let mut var_refundTxId = >::sse_decode(deserializer); - let mut var_refundTxAmountSat = >::sse_decode(deserializer); let mut var_paymentType = ::sse_decode(deserializer); let mut var_status = ::sse_decode(deserializer); + let mut var_details = >::sse_decode(deserializer); return crate::model::Payment { + destination: var_destination, tx_id: var_txId, - swap_id: var_swapId, timestamp: var_timestamp, amount_sat: var_amountSat, fees_sat: var_feesSat, - preimage: var_preimage, - bolt11: var_bolt11, - description: var_description, - refund_tx_id: var_refundTxId, - refund_tx_amount_sat: var_refundTxAmountSat, payment_type: var_paymentType, status: var_status, + details: var_details, }; } } +impl SseDecode for crate::model::PaymentDetails { + // Codec=Sse (Serialization based), see doc to use other codecs + fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self { + let mut tag_ = ::sse_decode(deserializer); + match tag_ { + 0 => { + let mut var_swapId = ::sse_decode(deserializer); + let mut var_description = ::sse_decode(deserializer); + let mut var_preimage = >::sse_decode(deserializer); + let mut var_bolt11 = >::sse_decode(deserializer); + let mut var_refundTxId = >::sse_decode(deserializer); + let mut var_refundTxAmountSat = >::sse_decode(deserializer); + return crate::model::PaymentDetails::Lightning { + swap_id: var_swapId, + description: var_description, + preimage: var_preimage, + bolt11: var_bolt11, + refund_tx_id: var_refundTxId, + refund_tx_amount_sat: var_refundTxAmountSat, + }; + } + 1 => { + let mut var_destination = ::sse_decode(deserializer); + let mut var_description = ::sse_decode(deserializer); + return crate::model::PaymentDetails::Liquid { + destination: var_destination, + description: var_description, + }; + } + 2 => { + let mut var_swapId = ::sse_decode(deserializer); + let mut var_description = ::sse_decode(deserializer); + let mut var_refundTxId = >::sse_decode(deserializer); + let mut var_refundTxAmountSat = >::sse_decode(deserializer); + return crate::model::PaymentDetails::Bitcoin { + swap_id: var_swapId, + description: var_description, + refund_tx_id: var_refundTxId, + refund_tx_amount_sat: var_refundTxAmountSat, + }; + } + _ => { + unimplemented!(""); + } + } + } +} + impl SseDecode for crate::error::PaymentError { // Codec=Sse (Serialization based), see doc to use other codecs fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self { @@ -3021,39 +2985,47 @@ impl SseDecode for crate::error::PaymentError { } 4 => { let mut var_err = ::sse_decode(deserializer); - return crate::error::PaymentError::Generic { err: var_err }; + return crate::error::PaymentError::AmountMissing { err: var_err }; } 5 => { - return crate::error::PaymentError::InvalidOrExpiredFees; + let mut var_err = ::sse_decode(deserializer); + return crate::error::PaymentError::InvalidNetwork { err: var_err }; } 6 => { - return crate::error::PaymentError::InsufficientFunds; + let mut var_err = ::sse_decode(deserializer); + return crate::error::PaymentError::Generic { err: var_err }; } 7 => { - let mut var_err = ::sse_decode(deserializer); - return crate::error::PaymentError::InvalidInvoice { err: var_err }; + return crate::error::PaymentError::InvalidOrExpiredFees; } 8 => { - return crate::error::PaymentError::InvalidPreimage; + return crate::error::PaymentError::InsufficientFunds; } 9 => { let mut var_err = ::sse_decode(deserializer); - return crate::error::PaymentError::LwkError { err: var_err }; + return crate::error::PaymentError::InvalidInvoice { err: var_err }; } 10 => { - return crate::error::PaymentError::PairsNotFound; + return crate::error::PaymentError::InvalidPreimage; } 11 => { - return crate::error::PaymentError::PaymentTimeout; + let mut var_err = ::sse_decode(deserializer); + return crate::error::PaymentError::LwkError { err: var_err }; } 12 => { - return crate::error::PaymentError::PersistError; + return crate::error::PaymentError::PairsNotFound; } 13 => { + return crate::error::PaymentError::PaymentTimeout; + } + 14 => { + return crate::error::PaymentError::PersistError; + } + 15 => { let mut var_err = ::sse_decode(deserializer); return crate::error::PaymentError::ReceiveError { err: var_err }; } - 14 => { + 16 => { let mut var_err = ::sse_decode(deserializer); let mut var_refundTxId = ::sse_decode(deserializer); return crate::error::PaymentError::Refunded { @@ -3061,14 +3033,14 @@ impl SseDecode for crate::error::PaymentError { refund_tx_id: var_refundTxId, }; } - 15 => { + 17 => { return crate::error::PaymentError::SelfTransferNotSupported; } - 16 => { + 18 => { let mut var_err = ::sse_decode(deserializer); return crate::error::PaymentError::SendError { err: var_err }; } - 17 => { + 19 => { let mut var_err = ::sse_decode(deserializer); return crate::error::PaymentError::SignerError { err: var_err }; } @@ -3079,6 +3051,19 @@ impl SseDecode for crate::error::PaymentError { } } +impl SseDecode for crate::model::PaymentMethod { + // Codec=Sse (Serialization based), see doc to use other codecs + fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self { + let mut inner = ::sse_decode(deserializer); + return match inner { + 0 => crate::model::PaymentMethod::Lightning, + 1 => crate::model::PaymentMethod::BitcoinAddress, + 2 => crate::model::PaymentMethod::LiquidAddress, + _ => unreachable!("Invalid variant for PaymentMethod: {}", inner), + }; + } +} + impl SseDecode for crate::model::PaymentState { // Codec=Sse (Serialization based), see doc to use other codecs fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self { @@ -3160,44 +3145,26 @@ impl SseDecode for crate::model::PreparePayOnchainResponse { } } -impl SseDecode for crate::model::PrepareReceiveOnchainRequest { +impl SseDecode for crate::model::PrepareReceiveRequest { // Codec=Sse (Serialization based), see doc to use other codecs fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self { - let mut var_payerAmountSat = ::sse_decode(deserializer); - return crate::model::PrepareReceiveOnchainRequest { + let mut var_payerAmountSat = >::sse_decode(deserializer); + let mut var_paymentMethod = ::sse_decode(deserializer); + return crate::model::PrepareReceiveRequest { payer_amount_sat: var_payerAmountSat, + payment_method: var_paymentMethod, }; } } -impl SseDecode for crate::model::PrepareReceiveOnchainResponse { +impl SseDecode for crate::model::PrepareReceiveResponse { // Codec=Sse (Serialization based), see doc to use other codecs fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self { - let mut var_payerAmountSat = ::sse_decode(deserializer); + let mut var_paymentMethod = ::sse_decode(deserializer); + let mut var_payerAmountSat = >::sse_decode(deserializer); let mut var_feesSat = ::sse_decode(deserializer); - return crate::model::PrepareReceiveOnchainResponse { - payer_amount_sat: var_payerAmountSat, - fees_sat: var_feesSat, - }; - } -} - -impl SseDecode for crate::model::PrepareReceivePaymentRequest { - // Codec=Sse (Serialization based), see doc to use other codecs - fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self { - let mut var_payerAmountSat = ::sse_decode(deserializer); - return crate::model::PrepareReceivePaymentRequest { - payer_amount_sat: var_payerAmountSat, - }; - } -} - -impl SseDecode for crate::model::PrepareReceivePaymentResponse { - // Codec=Sse (Serialization based), see doc to use other codecs - fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self { - let mut var_payerAmountSat = ::sse_decode(deserializer); - let mut var_feesSat = ::sse_decode(deserializer); - return crate::model::PrepareReceivePaymentResponse { + return crate::model::PrepareReceiveResponse { + payment_method: var_paymentMethod, payer_amount_sat: var_payerAmountSat, fees_sat: var_feesSat, }; @@ -3235,9 +3202,11 @@ impl SseDecode for crate::model::PrepareRefundResponse { impl SseDecode for crate::model::PrepareSendRequest { // Codec=Sse (Serialization based), see doc to use other codecs fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self { - let mut var_invoice = ::sse_decode(deserializer); + let mut var_destination = ::sse_decode(deserializer); + let mut var_amountSat = >::sse_decode(deserializer); return crate::model::PrepareSendRequest { - invoice: var_invoice, + destination: var_destination, + amount_sat: var_amountSat, }; } } @@ -3245,10 +3214,10 @@ impl SseDecode for crate::model::PrepareSendRequest { impl SseDecode for crate::model::PrepareSendResponse { // Codec=Sse (Serialization based), see doc to use other codecs fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self { - let mut var_invoice = ::sse_decode(deserializer); + let mut var_destination = ::sse_decode(deserializer); let mut var_feesSat = ::sse_decode(deserializer); return crate::model::PrepareSendResponse { - invoice: var_invoice, + destination: var_destination, fees_sat: var_feesSat, }; } @@ -3266,27 +3235,15 @@ impl SseDecode for crate::bindings::Rate { } } -impl SseDecode for crate::model::ReceiveOnchainResponse { - // Codec=Sse (Serialization based), see doc to use other codecs - fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self { - let mut var_address = ::sse_decode(deserializer); - let mut var_bip21 = ::sse_decode(deserializer); - return crate::model::ReceiveOnchainResponse { - address: var_address, - bip21: var_bip21, - }; - } -} - impl SseDecode for crate::model::ReceivePaymentRequest { // Codec=Sse (Serialization based), see doc to use other codecs fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self { let mut var_description = >::sse_decode(deserializer); - let mut var_prepareRes = - ::sse_decode(deserializer); + let mut var_prepareResponse = + ::sse_decode(deserializer); return crate::model::ReceivePaymentRequest { description: var_description, - prepare_res: var_prepareRes, + prepare_response: var_prepareResponse, }; } } @@ -3294,11 +3251,9 @@ impl SseDecode for crate::model::ReceivePaymentRequest { impl SseDecode for crate::model::ReceivePaymentResponse { // Codec=Sse (Serialization based), see doc to use other codecs fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self { - let mut var_id = ::sse_decode(deserializer); - let mut var_invoice = ::sse_decode(deserializer); + let mut var_destination = ::sse_decode(deserializer); return crate::model::ReceivePaymentResponse { - id: var_id, - invoice: var_invoice, + destination: var_destination, }; } } @@ -3476,6 +3431,41 @@ impl SseDecode for crate::model::SdkEvent { } } +impl SseDecode for crate::model::SendDestination { + // Codec=Sse (Serialization based), see doc to use other codecs + fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self { + let mut tag_ = ::sse_decode(deserializer); + match tag_ { + 0 => { + let mut var_addressData = + ::sse_decode(deserializer); + return crate::model::SendDestination::LiquidAddress { + address_data: var_addressData, + }; + } + 1 => { + let mut var_invoice = ::sse_decode(deserializer); + return crate::model::SendDestination::Bolt11 { + invoice: var_invoice, + }; + } + _ => { + unimplemented!(""); + } + } + } +} + +impl SseDecode for crate::model::SendPaymentRequest { + // Codec=Sse (Serialization based), see doc to use other codecs + fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self { + let mut var_prepareResponse = ::sse_decode(deserializer); + return crate::model::SendPaymentRequest { + prepare_response: var_prepareResponse, + }; + } +} + impl SseDecode for crate::model::SendPaymentResponse { // Codec=Sse (Serialization based), see doc to use other codecs fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self { @@ -3752,7 +3742,7 @@ impl flutter_rust_bridge::IntoIntoDart impl flutter_rust_bridge::IntoDart for crate::model::BuyBitcoinRequest { fn into_dart(self) -> flutter_rust_bridge::for_generated::DartAbi { [ - self.prepare_res.into_into_dart().into_dart(), + self.prepare_response.into_into_dart().into_dart(), self.redirect_url.into_into_dart().into_dart(), ] .into_dart() @@ -4596,7 +4586,7 @@ impl flutter_rust_bridge::IntoDart for crate::model::PayOnchainRequest { fn into_dart(self) -> flutter_rust_bridge::for_generated::DartAbi { [ self.address.into_into_dart().into_dart(), - self.prepare_res.into_into_dart().into_dart(), + self.prepare_response.into_into_dart().into_dart(), ] .into_dart() } @@ -4616,18 +4606,14 @@ impl flutter_rust_bridge::IntoIntoDart impl flutter_rust_bridge::IntoDart for crate::model::Payment { fn into_dart(self) -> flutter_rust_bridge::for_generated::DartAbi { [ + self.destination.into_into_dart().into_dart(), self.tx_id.into_into_dart().into_dart(), - self.swap_id.into_into_dart().into_dart(), self.timestamp.into_into_dart().into_dart(), self.amount_sat.into_into_dart().into_dart(), self.fees_sat.into_into_dart().into_dart(), - self.preimage.into_into_dart().into_dart(), - self.bolt11.into_into_dart().into_dart(), - self.description.into_into_dart().into_dart(), - self.refund_tx_id.into_into_dart().into_dart(), - self.refund_tx_amount_sat.into_into_dart().into_dart(), self.payment_type.into_into_dart().into_dart(), self.status.into_into_dart().into_dart(), + self.details.into_into_dart().into_dart(), ] .into_dart() } @@ -4639,6 +4625,63 @@ impl flutter_rust_bridge::IntoIntoDart for crate::model:: } } // Codec=Dco (DartCObject based), see doc to use other codecs +impl flutter_rust_bridge::IntoDart for crate::model::PaymentDetails { + fn into_dart(self) -> flutter_rust_bridge::for_generated::DartAbi { + match self { + crate::model::PaymentDetails::Lightning { + swap_id, + description, + preimage, + bolt11, + refund_tx_id, + refund_tx_amount_sat, + } => [ + 0.into_dart(), + swap_id.into_into_dart().into_dart(), + description.into_into_dart().into_dart(), + preimage.into_into_dart().into_dart(), + bolt11.into_into_dart().into_dart(), + refund_tx_id.into_into_dart().into_dart(), + refund_tx_amount_sat.into_into_dart().into_dart(), + ] + .into_dart(), + crate::model::PaymentDetails::Liquid { + destination, + description, + } => [ + 1.into_dart(), + destination.into_into_dart().into_dart(), + description.into_into_dart().into_dart(), + ] + .into_dart(), + crate::model::PaymentDetails::Bitcoin { + swap_id, + description, + refund_tx_id, + refund_tx_amount_sat, + } => [ + 2.into_dart(), + swap_id.into_into_dart().into_dart(), + description.into_into_dart().into_dart(), + refund_tx_id.into_into_dart().into_dart(), + refund_tx_amount_sat.into_into_dart().into_dart(), + ] + .into_dart(), + _ => { + unimplemented!(""); + } + } + } +} +impl flutter_rust_bridge::for_generated::IntoDartExceptPrimitive for crate::model::PaymentDetails {} +impl flutter_rust_bridge::IntoIntoDart + for crate::model::PaymentDetails +{ + fn into_into_dart(self) -> crate::model::PaymentDetails { + self + } +} +// Codec=Dco (DartCObject based), see doc to use other codecs impl flutter_rust_bridge::IntoDart for crate::error::PaymentError { fn into_dart(self) -> flutter_rust_bridge::for_generated::DartAbi { match self { @@ -4646,36 +4689,42 @@ impl flutter_rust_bridge::IntoDart for crate::error::PaymentError { crate::error::PaymentError::AlreadyPaid => [1.into_dart()].into_dart(), crate::error::PaymentError::PaymentInProgress => [2.into_dart()].into_dart(), crate::error::PaymentError::AmountOutOfRange => [3.into_dart()].into_dart(), - crate::error::PaymentError::Generic { err } => { + crate::error::PaymentError::AmountMissing { err } => { [4.into_dart(), err.into_into_dart().into_dart()].into_dart() } - crate::error::PaymentError::InvalidOrExpiredFees => [5.into_dart()].into_dart(), - crate::error::PaymentError::InsufficientFunds => [6.into_dart()].into_dart(), - crate::error::PaymentError::InvalidInvoice { err } => { - [7.into_dart(), err.into_into_dart().into_dart()].into_dart() + crate::error::PaymentError::InvalidNetwork { err } => { + [5.into_dart(), err.into_into_dart().into_dart()].into_dart() } - crate::error::PaymentError::InvalidPreimage => [8.into_dart()].into_dart(), - crate::error::PaymentError::LwkError { err } => { + crate::error::PaymentError::Generic { err } => { + [6.into_dart(), err.into_into_dart().into_dart()].into_dart() + } + crate::error::PaymentError::InvalidOrExpiredFees => [7.into_dart()].into_dart(), + crate::error::PaymentError::InsufficientFunds => [8.into_dart()].into_dart(), + crate::error::PaymentError::InvalidInvoice { err } => { [9.into_dart(), err.into_into_dart().into_dart()].into_dart() } - crate::error::PaymentError::PairsNotFound => [10.into_dart()].into_dart(), - crate::error::PaymentError::PaymentTimeout => [11.into_dart()].into_dart(), - crate::error::PaymentError::PersistError => [12.into_dart()].into_dart(), + crate::error::PaymentError::InvalidPreimage => [10.into_dart()].into_dart(), + crate::error::PaymentError::LwkError { err } => { + [11.into_dart(), err.into_into_dart().into_dart()].into_dart() + } + crate::error::PaymentError::PairsNotFound => [12.into_dart()].into_dart(), + crate::error::PaymentError::PaymentTimeout => [13.into_dart()].into_dart(), + crate::error::PaymentError::PersistError => [14.into_dart()].into_dart(), crate::error::PaymentError::ReceiveError { err } => { - [13.into_dart(), err.into_into_dart().into_dart()].into_dart() + [15.into_dart(), err.into_into_dart().into_dart()].into_dart() } crate::error::PaymentError::Refunded { err, refund_tx_id } => [ - 14.into_dart(), + 16.into_dart(), err.into_into_dart().into_dart(), refund_tx_id.into_into_dart().into_dart(), ] .into_dart(), - crate::error::PaymentError::SelfTransferNotSupported => [15.into_dart()].into_dart(), + crate::error::PaymentError::SelfTransferNotSupported => [17.into_dart()].into_dart(), crate::error::PaymentError::SendError { err } => { - [16.into_dart(), err.into_into_dart().into_dart()].into_dart() + [18.into_dart(), err.into_into_dart().into_dart()].into_dart() } crate::error::PaymentError::SignerError { err } => { - [17.into_dart(), err.into_into_dart().into_dart()].into_dart() + [19.into_dart(), err.into_into_dart().into_dart()].into_dart() } _ => { unimplemented!(""); @@ -4690,6 +4739,25 @@ impl flutter_rust_bridge::IntoIntoDart for crate::er } } // Codec=Dco (DartCObject based), see doc to use other codecs +impl flutter_rust_bridge::IntoDart for crate::model::PaymentMethod { + fn into_dart(self) -> flutter_rust_bridge::for_generated::DartAbi { + match self { + Self::Lightning => 0.into_dart(), + Self::BitcoinAddress => 1.into_dart(), + Self::LiquidAddress => 2.into_dart(), + _ => unreachable!(), + } + } +} +impl flutter_rust_bridge::for_generated::IntoDartExceptPrimitive for crate::model::PaymentMethod {} +impl flutter_rust_bridge::IntoIntoDart + for crate::model::PaymentMethod +{ + fn into_into_dart(self) -> crate::model::PaymentMethod { + self + } +} +// Codec=Dco (DartCObject based), see doc to use other codecs impl flutter_rust_bridge::IntoDart for crate::model::PaymentState { fn into_dart(self) -> flutter_rust_bridge::for_generated::DartAbi { match self { @@ -4813,26 +4881,31 @@ impl flutter_rust_bridge::IntoIntoDart } } // Codec=Dco (DartCObject based), see doc to use other codecs -impl flutter_rust_bridge::IntoDart for crate::model::PrepareReceiveOnchainRequest { +impl flutter_rust_bridge::IntoDart for crate::model::PrepareReceiveRequest { fn into_dart(self) -> flutter_rust_bridge::for_generated::DartAbi { - [self.payer_amount_sat.into_into_dart().into_dart()].into_dart() + [ + self.payer_amount_sat.into_into_dart().into_dart(), + self.payment_method.into_into_dart().into_dart(), + ] + .into_dart() } } impl flutter_rust_bridge::for_generated::IntoDartExceptPrimitive - for crate::model::PrepareReceiveOnchainRequest + for crate::model::PrepareReceiveRequest { } -impl flutter_rust_bridge::IntoIntoDart - for crate::model::PrepareReceiveOnchainRequest +impl flutter_rust_bridge::IntoIntoDart + for crate::model::PrepareReceiveRequest { - fn into_into_dart(self) -> crate::model::PrepareReceiveOnchainRequest { + fn into_into_dart(self) -> crate::model::PrepareReceiveRequest { self } } // Codec=Dco (DartCObject based), see doc to use other codecs -impl flutter_rust_bridge::IntoDart for crate::model::PrepareReceiveOnchainResponse { +impl flutter_rust_bridge::IntoDart for crate::model::PrepareReceiveResponse { fn into_dart(self) -> flutter_rust_bridge::for_generated::DartAbi { [ + self.payment_method.into_into_dart().into_dart(), self.payer_amount_sat.into_into_dart().into_dart(), self.fees_sat.into_into_dart().into_dart(), ] @@ -4840,51 +4913,13 @@ impl flutter_rust_bridge::IntoDart for crate::model::PrepareReceiveOnchainRespon } } impl flutter_rust_bridge::for_generated::IntoDartExceptPrimitive - for crate::model::PrepareReceiveOnchainResponse + for crate::model::PrepareReceiveResponse { } -impl flutter_rust_bridge::IntoIntoDart - for crate::model::PrepareReceiveOnchainResponse +impl flutter_rust_bridge::IntoIntoDart + for crate::model::PrepareReceiveResponse { - fn into_into_dart(self) -> crate::model::PrepareReceiveOnchainResponse { - self - } -} -// Codec=Dco (DartCObject based), see doc to use other codecs -impl flutter_rust_bridge::IntoDart for crate::model::PrepareReceivePaymentRequest { - fn into_dart(self) -> flutter_rust_bridge::for_generated::DartAbi { - [self.payer_amount_sat.into_into_dart().into_dart()].into_dart() - } -} -impl flutter_rust_bridge::for_generated::IntoDartExceptPrimitive - for crate::model::PrepareReceivePaymentRequest -{ -} -impl flutter_rust_bridge::IntoIntoDart - for crate::model::PrepareReceivePaymentRequest -{ - fn into_into_dart(self) -> crate::model::PrepareReceivePaymentRequest { - self - } -} -// Codec=Dco (DartCObject based), see doc to use other codecs -impl flutter_rust_bridge::IntoDart for crate::model::PrepareReceivePaymentResponse { - fn into_dart(self) -> flutter_rust_bridge::for_generated::DartAbi { - [ - self.payer_amount_sat.into_into_dart().into_dart(), - self.fees_sat.into_into_dart().into_dart(), - ] - .into_dart() - } -} -impl flutter_rust_bridge::for_generated::IntoDartExceptPrimitive - for crate::model::PrepareReceivePaymentResponse -{ -} -impl flutter_rust_bridge::IntoIntoDart - for crate::model::PrepareReceivePaymentResponse -{ - fn into_into_dart(self) -> crate::model::PrepareReceivePaymentResponse { + fn into_into_dart(self) -> crate::model::PrepareReceiveResponse { self } } @@ -4935,7 +4970,11 @@ impl flutter_rust_bridge::IntoIntoDart // Codec=Dco (DartCObject based), see doc to use other codecs impl flutter_rust_bridge::IntoDart for crate::model::PrepareSendRequest { fn into_dart(self) -> flutter_rust_bridge::for_generated::DartAbi { - [self.invoice.into_into_dart().into_dart()].into_dart() + [ + self.destination.into_into_dart().into_dart(), + self.amount_sat.into_into_dart().into_dart(), + ] + .into_dart() } } impl flutter_rust_bridge::for_generated::IntoDartExceptPrimitive @@ -4953,7 +4992,7 @@ impl flutter_rust_bridge::IntoIntoDart impl flutter_rust_bridge::IntoDart for crate::model::PrepareSendResponse { fn into_dart(self) -> flutter_rust_bridge::for_generated::DartAbi { [ - self.invoice.into_into_dart().into_dart(), + self.destination.into_into_dart().into_dart(), self.fees_sat.into_into_dart().into_dart(), ] .into_dart() @@ -4992,32 +5031,11 @@ impl flutter_rust_bridge::IntoIntoDart> } } // Codec=Dco (DartCObject based), see doc to use other codecs -impl flutter_rust_bridge::IntoDart for crate::model::ReceiveOnchainResponse { - fn into_dart(self) -> flutter_rust_bridge::for_generated::DartAbi { - [ - self.address.into_into_dart().into_dart(), - self.bip21.into_into_dart().into_dart(), - ] - .into_dart() - } -} -impl flutter_rust_bridge::for_generated::IntoDartExceptPrimitive - for crate::model::ReceiveOnchainResponse -{ -} -impl flutter_rust_bridge::IntoIntoDart - for crate::model::ReceiveOnchainResponse -{ - fn into_into_dart(self) -> crate::model::ReceiveOnchainResponse { - self - } -} -// Codec=Dco (DartCObject based), see doc to use other codecs impl flutter_rust_bridge::IntoDart for crate::model::ReceivePaymentRequest { fn into_dart(self) -> flutter_rust_bridge::for_generated::DartAbi { [ self.description.into_into_dart().into_dart(), - self.prepare_res.into_into_dart().into_dart(), + self.prepare_response.into_into_dart().into_dart(), ] .into_dart() } @@ -5036,11 +5054,7 @@ impl flutter_rust_bridge::IntoIntoDart // Codec=Dco (DartCObject based), see doc to use other codecs impl flutter_rust_bridge::IntoDart for crate::model::ReceivePaymentResponse { fn into_dart(self) -> flutter_rust_bridge::for_generated::DartAbi { - [ - self.id.into_into_dart().into_dart(), - self.invoice.into_into_dart().into_dart(), - ] - .into_dart() + [self.destination.into_into_dart().into_dart()].into_dart() } } impl flutter_rust_bridge::for_generated::IntoDartExceptPrimitive @@ -5247,6 +5261,47 @@ impl flutter_rust_bridge::IntoIntoDart for crate::model: } } // Codec=Dco (DartCObject based), see doc to use other codecs +impl flutter_rust_bridge::IntoDart for crate::model::SendDestination { + fn into_dart(self) -> flutter_rust_bridge::for_generated::DartAbi { + match self { + crate::model::SendDestination::LiquidAddress { address_data } => { + [0.into_dart(), address_data.into_into_dart().into_dart()].into_dart() + } + crate::model::SendDestination::Bolt11 { invoice } => { + [1.into_dart(), invoice.into_into_dart().into_dart()].into_dart() + } + _ => { + unimplemented!(""); + } + } + } +} +impl flutter_rust_bridge::for_generated::IntoDartExceptPrimitive for crate::model::SendDestination {} +impl flutter_rust_bridge::IntoIntoDart + for crate::model::SendDestination +{ + fn into_into_dart(self) -> crate::model::SendDestination { + self + } +} +// Codec=Dco (DartCObject based), see doc to use other codecs +impl flutter_rust_bridge::IntoDart for crate::model::SendPaymentRequest { + fn into_dart(self) -> flutter_rust_bridge::for_generated::DartAbi { + [self.prepare_response.into_into_dart().into_dart()].into_dart() + } +} +impl flutter_rust_bridge::for_generated::IntoDartExceptPrimitive + for crate::model::SendPaymentRequest +{ +} +impl flutter_rust_bridge::IntoIntoDart + for crate::model::SendPaymentRequest +{ + fn into_into_dart(self) -> crate::model::SendPaymentRequest { + self + } +} +// Codec=Dco (DartCObject based), see doc to use other codecs impl flutter_rust_bridge::IntoDart for crate::model::SendPaymentResponse { fn into_dart(self) -> flutter_rust_bridge::for_generated::DartAbi { [self.payment.into_into_dart().into_dart()].into_dart() @@ -5466,7 +5521,7 @@ impl SseEncode for crate::model::BuyBitcoinProvider { impl SseEncode for crate::model::BuyBitcoinRequest { // Codec=Sse (Serialization based), see doc to use other codecs fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) { - ::sse_encode(self.prepare_res, serializer); + ::sse_encode(self.prepare_response, serializer); >::sse_encode(self.redirect_url, serializer); } } @@ -6127,6 +6182,16 @@ impl SseEncode for Option { } } +impl SseEncode for Option { + // Codec=Sse (Serialization based), see doc to use other codecs + fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) { + ::sse_encode(self.is_some(), serializer); + if let Some(value) = self { + ::sse_encode(value, serializer); + } + } +} + impl SseEncode for Option { // Codec=Sse (Serialization based), see doc to use other codecs fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) { @@ -6181,25 +6246,68 @@ impl SseEncode for crate::model::PayOnchainRequest { // Codec=Sse (Serialization based), see doc to use other codecs fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) { ::sse_encode(self.address, serializer); - ::sse_encode(self.prepare_res, serializer); + ::sse_encode(self.prepare_response, serializer); } } impl SseEncode for crate::model::Payment { // Codec=Sse (Serialization based), see doc to use other codecs fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) { + >::sse_encode(self.destination, serializer); >::sse_encode(self.tx_id, serializer); - >::sse_encode(self.swap_id, serializer); ::sse_encode(self.timestamp, serializer); ::sse_encode(self.amount_sat, serializer); ::sse_encode(self.fees_sat, serializer); - >::sse_encode(self.preimage, serializer); - >::sse_encode(self.bolt11, serializer); - ::sse_encode(self.description, serializer); - >::sse_encode(self.refund_tx_id, serializer); - >::sse_encode(self.refund_tx_amount_sat, serializer); ::sse_encode(self.payment_type, serializer); ::sse_encode(self.status, serializer); + >::sse_encode(self.details, serializer); + } +} + +impl SseEncode for crate::model::PaymentDetails { + // Codec=Sse (Serialization based), see doc to use other codecs + fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) { + match self { + crate::model::PaymentDetails::Lightning { + swap_id, + description, + preimage, + bolt11, + refund_tx_id, + refund_tx_amount_sat, + } => { + ::sse_encode(0, serializer); + ::sse_encode(swap_id, serializer); + ::sse_encode(description, serializer); + >::sse_encode(preimage, serializer); + >::sse_encode(bolt11, serializer); + >::sse_encode(refund_tx_id, serializer); + >::sse_encode(refund_tx_amount_sat, serializer); + } + crate::model::PaymentDetails::Liquid { + destination, + description, + } => { + ::sse_encode(1, serializer); + ::sse_encode(destination, serializer); + ::sse_encode(description, serializer); + } + crate::model::PaymentDetails::Bitcoin { + swap_id, + description, + refund_tx_id, + refund_tx_amount_sat, + } => { + ::sse_encode(2, serializer); + ::sse_encode(swap_id, serializer); + ::sse_encode(description, serializer); + >::sse_encode(refund_tx_id, serializer); + >::sse_encode(refund_tx_amount_sat, serializer); + } + _ => { + unimplemented!(""); + } + } } } @@ -6219,54 +6327,62 @@ impl SseEncode for crate::error::PaymentError { crate::error::PaymentError::AmountOutOfRange => { ::sse_encode(3, serializer); } - crate::error::PaymentError::Generic { err } => { + crate::error::PaymentError::AmountMissing { err } => { ::sse_encode(4, serializer); ::sse_encode(err, serializer); } - crate::error::PaymentError::InvalidOrExpiredFees => { + crate::error::PaymentError::InvalidNetwork { err } => { ::sse_encode(5, serializer); - } - crate::error::PaymentError::InsufficientFunds => { - ::sse_encode(6, serializer); - } - crate::error::PaymentError::InvalidInvoice { err } => { - ::sse_encode(7, serializer); ::sse_encode(err, serializer); } - crate::error::PaymentError::InvalidPreimage => { + crate::error::PaymentError::Generic { err } => { + ::sse_encode(6, serializer); + ::sse_encode(err, serializer); + } + crate::error::PaymentError::InvalidOrExpiredFees => { + ::sse_encode(7, serializer); + } + crate::error::PaymentError::InsufficientFunds => { ::sse_encode(8, serializer); } - crate::error::PaymentError::LwkError { err } => { + crate::error::PaymentError::InvalidInvoice { err } => { ::sse_encode(9, serializer); ::sse_encode(err, serializer); } - crate::error::PaymentError::PairsNotFound => { + crate::error::PaymentError::InvalidPreimage => { ::sse_encode(10, serializer); } - crate::error::PaymentError::PaymentTimeout => { + crate::error::PaymentError::LwkError { err } => { ::sse_encode(11, serializer); + ::sse_encode(err, serializer); } - crate::error::PaymentError::PersistError => { + crate::error::PaymentError::PairsNotFound => { ::sse_encode(12, serializer); } - crate::error::PaymentError::ReceiveError { err } => { + crate::error::PaymentError::PaymentTimeout => { ::sse_encode(13, serializer); + } + crate::error::PaymentError::PersistError => { + ::sse_encode(14, serializer); + } + crate::error::PaymentError::ReceiveError { err } => { + ::sse_encode(15, serializer); ::sse_encode(err, serializer); } crate::error::PaymentError::Refunded { err, refund_tx_id } => { - ::sse_encode(14, serializer); + ::sse_encode(16, serializer); ::sse_encode(err, serializer); ::sse_encode(refund_tx_id, serializer); } crate::error::PaymentError::SelfTransferNotSupported => { - ::sse_encode(15, serializer); + ::sse_encode(17, serializer); } crate::error::PaymentError::SendError { err } => { - ::sse_encode(16, serializer); + ::sse_encode(18, serializer); ::sse_encode(err, serializer); } crate::error::PaymentError::SignerError { err } => { - ::sse_encode(17, serializer); + ::sse_encode(19, serializer); ::sse_encode(err, serializer); } _ => { @@ -6276,6 +6392,23 @@ impl SseEncode for crate::error::PaymentError { } } +impl SseEncode for crate::model::PaymentMethod { + // Codec=Sse (Serialization based), see doc to use other codecs + fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) { + ::sse_encode( + match self { + crate::model::PaymentMethod::Lightning => 0, + crate::model::PaymentMethod::BitcoinAddress => 1, + crate::model::PaymentMethod::LiquidAddress => 2, + _ => { + unimplemented!(""); + } + }, + serializer, + ); + } +} + impl SseEncode for crate::model::PaymentState { // Codec=Sse (Serialization based), see doc to use other codecs fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) { @@ -6347,32 +6480,19 @@ impl SseEncode for crate::model::PreparePayOnchainResponse { } } -impl SseEncode for crate::model::PrepareReceiveOnchainRequest { +impl SseEncode for crate::model::PrepareReceiveRequest { // Codec=Sse (Serialization based), see doc to use other codecs fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) { - ::sse_encode(self.payer_amount_sat, serializer); + >::sse_encode(self.payer_amount_sat, serializer); + ::sse_encode(self.payment_method, serializer); } } -impl SseEncode for crate::model::PrepareReceiveOnchainResponse { +impl SseEncode for crate::model::PrepareReceiveResponse { // Codec=Sse (Serialization based), see doc to use other codecs fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) { - ::sse_encode(self.payer_amount_sat, serializer); - ::sse_encode(self.fees_sat, serializer); - } -} - -impl SseEncode for crate::model::PrepareReceivePaymentRequest { - // Codec=Sse (Serialization based), see doc to use other codecs - fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) { - ::sse_encode(self.payer_amount_sat, serializer); - } -} - -impl SseEncode for crate::model::PrepareReceivePaymentResponse { - // Codec=Sse (Serialization based), see doc to use other codecs - fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) { - ::sse_encode(self.payer_amount_sat, serializer); + ::sse_encode(self.payment_method, serializer); + >::sse_encode(self.payer_amount_sat, serializer); ::sse_encode(self.fees_sat, serializer); } } @@ -6398,14 +6518,15 @@ impl SseEncode for crate::model::PrepareRefundResponse { impl SseEncode for crate::model::PrepareSendRequest { // Codec=Sse (Serialization based), see doc to use other codecs fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) { - ::sse_encode(self.invoice, serializer); + ::sse_encode(self.destination, serializer); + >::sse_encode(self.amount_sat, serializer); } } impl SseEncode for crate::model::PrepareSendResponse { // Codec=Sse (Serialization based), see doc to use other codecs fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) { - ::sse_encode(self.invoice, serializer); + ::sse_encode(self.destination, serializer); ::sse_encode(self.fees_sat, serializer); } } @@ -6418,27 +6539,18 @@ impl SseEncode for crate::bindings::Rate { } } -impl SseEncode for crate::model::ReceiveOnchainResponse { - // Codec=Sse (Serialization based), see doc to use other codecs - fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) { - ::sse_encode(self.address, serializer); - ::sse_encode(self.bip21, serializer); - } -} - impl SseEncode for crate::model::ReceivePaymentRequest { // Codec=Sse (Serialization based), see doc to use other codecs fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) { >::sse_encode(self.description, serializer); - ::sse_encode(self.prepare_res, serializer); + ::sse_encode(self.prepare_response, serializer); } } impl SseEncode for crate::model::ReceivePaymentResponse { // Codec=Sse (Serialization based), see doc to use other codecs fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) { - ::sse_encode(self.id, serializer); - ::sse_encode(self.invoice, serializer); + ::sse_encode(self.destination, serializer); } } @@ -6568,6 +6680,32 @@ impl SseEncode for crate::model::SdkEvent { } } +impl SseEncode for crate::model::SendDestination { + // Codec=Sse (Serialization based), see doc to use other codecs + fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) { + match self { + crate::model::SendDestination::LiquidAddress { address_data } => { + ::sse_encode(0, serializer); + ::sse_encode(address_data, serializer); + } + crate::model::SendDestination::Bolt11 { invoice } => { + ::sse_encode(1, serializer); + ::sse_encode(invoice, serializer); + } + _ => { + unimplemented!(""); + } + } + } +} + +impl SseEncode for crate::model::SendPaymentRequest { + // Codec=Sse (Serialization based), see doc to use other codecs + fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) { + ::sse_encode(self.prepare_response, serializer); + } +} + impl SseEncode for crate::model::SendPaymentResponse { // Codec=Sse (Serialization based), see doc to use other codecs fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) { @@ -6986,6 +7124,13 @@ mod io { CstDecode::::cst_decode(*wrap).into() } } + impl CstDecode for *mut wire_cst_payment_details { + // Codec=Cst (C-struct based), see doc to use other codecs + fn cst_decode(self) -> crate::model::PaymentDetails { + let wrap = unsafe { flutter_rust_bridge::for_generated::box_from_leak_ptr(self) }; + CstDecode::::cst_decode(*wrap).into() + } + } impl CstDecode for *mut wire_cst_prepare_buy_bitcoin_request { @@ -7004,31 +7149,11 @@ mod io { CstDecode::::cst_decode(*wrap).into() } } - impl CstDecode - for *mut wire_cst_prepare_receive_onchain_request - { + impl CstDecode for *mut wire_cst_prepare_receive_request { // Codec=Cst (C-struct based), see doc to use other codecs - fn cst_decode(self) -> crate::model::PrepareReceiveOnchainRequest { + fn cst_decode(self) -> crate::model::PrepareReceiveRequest { let wrap = unsafe { flutter_rust_bridge::for_generated::box_from_leak_ptr(self) }; - CstDecode::::cst_decode(*wrap).into() - } - } - impl CstDecode - for *mut wire_cst_prepare_receive_onchain_response - { - // Codec=Cst (C-struct based), see doc to use other codecs - fn cst_decode(self) -> crate::model::PrepareReceiveOnchainResponse { - let wrap = unsafe { flutter_rust_bridge::for_generated::box_from_leak_ptr(self) }; - CstDecode::::cst_decode(*wrap).into() - } - } - impl CstDecode - for *mut wire_cst_prepare_receive_payment_request - { - // Codec=Cst (C-struct based), see doc to use other codecs - fn cst_decode(self) -> crate::model::PrepareReceivePaymentRequest { - let wrap = unsafe { flutter_rust_bridge::for_generated::box_from_leak_ptr(self) }; - CstDecode::::cst_decode(*wrap).into() + CstDecode::::cst_decode(*wrap).into() } } impl CstDecode for *mut wire_cst_prepare_refund_request { @@ -7045,13 +7170,6 @@ mod io { CstDecode::::cst_decode(*wrap).into() } } - impl CstDecode for *mut wire_cst_prepare_send_response { - // Codec=Cst (C-struct based), see doc to use other codecs - fn cst_decode(self) -> crate::model::PrepareSendResponse { - let wrap = unsafe { flutter_rust_bridge::for_generated::box_from_leak_ptr(self) }; - CstDecode::::cst_decode(*wrap).into() - } - } impl CstDecode for *mut wire_cst_receive_payment_request { // Codec=Cst (C-struct based), see doc to use other codecs fn cst_decode(self) -> crate::model::ReceivePaymentRequest { @@ -7080,6 +7198,13 @@ mod io { CstDecode::::cst_decode(*wrap).into() } } + impl CstDecode for *mut wire_cst_send_payment_request { + // Codec=Cst (C-struct based), see doc to use other codecs + fn cst_decode(self) -> crate::model::SendPaymentRequest { + let wrap = unsafe { flutter_rust_bridge::for_generated::box_from_leak_ptr(self) }; + CstDecode::::cst_decode(*wrap).into() + } + } impl CstDecode for *mut wire_cst_success_action_processed { // Codec=Cst (C-struct based), see doc to use other codecs fn cst_decode(self) -> crate::bindings::SuccessActionProcessed { @@ -7117,7 +7242,7 @@ mod io { // Codec=Cst (C-struct based), see doc to use other codecs fn cst_decode(self) -> crate::model::BuyBitcoinRequest { crate::model::BuyBitcoinRequest { - prepare_res: self.prepare_res.cst_decode(), + prepare_response: self.prepare_response.cst_decode(), redirect_url: self.redirect_url.cst_decode(), } } @@ -7773,7 +7898,7 @@ mod io { fn cst_decode(self) -> crate::model::PayOnchainRequest { crate::model::PayOnchainRequest { address: self.address.cst_decode(), - prepare_res: self.prepare_res.cst_decode(), + prepare_response: self.prepare_response.cst_decode(), } } } @@ -7781,18 +7906,49 @@ mod io { // Codec=Cst (C-struct based), see doc to use other codecs fn cst_decode(self) -> crate::model::Payment { crate::model::Payment { + destination: self.destination.cst_decode(), tx_id: self.tx_id.cst_decode(), - swap_id: self.swap_id.cst_decode(), timestamp: self.timestamp.cst_decode(), amount_sat: self.amount_sat.cst_decode(), fees_sat: self.fees_sat.cst_decode(), - preimage: self.preimage.cst_decode(), - bolt11: self.bolt11.cst_decode(), - description: self.description.cst_decode(), - refund_tx_id: self.refund_tx_id.cst_decode(), - refund_tx_amount_sat: self.refund_tx_amount_sat.cst_decode(), payment_type: self.payment_type.cst_decode(), status: self.status.cst_decode(), + details: self.details.cst_decode(), + } + } + } + impl CstDecode for wire_cst_payment_details { + // Codec=Cst (C-struct based), see doc to use other codecs + fn cst_decode(self) -> crate::model::PaymentDetails { + match self.tag { + 0 => { + let ans = unsafe { self.kind.Lightning }; + crate::model::PaymentDetails::Lightning { + swap_id: ans.swap_id.cst_decode(), + description: ans.description.cst_decode(), + preimage: ans.preimage.cst_decode(), + bolt11: ans.bolt11.cst_decode(), + refund_tx_id: ans.refund_tx_id.cst_decode(), + refund_tx_amount_sat: ans.refund_tx_amount_sat.cst_decode(), + } + } + 1 => { + let ans = unsafe { self.kind.Liquid }; + crate::model::PaymentDetails::Liquid { + destination: ans.destination.cst_decode(), + description: ans.description.cst_decode(), + } + } + 2 => { + let ans = unsafe { self.kind.Bitcoin }; + crate::model::PaymentDetails::Bitcoin { + swap_id: ans.swap_id.cst_decode(), + description: ans.description.cst_decode(), + refund_tx_id: ans.refund_tx_id.cst_decode(), + refund_tx_amount_sat: ans.refund_tx_amount_sat.cst_decode(), + } + } + _ => unreachable!(), } } } @@ -7805,50 +7961,62 @@ mod io { 2 => crate::error::PaymentError::PaymentInProgress, 3 => crate::error::PaymentError::AmountOutOfRange, 4 => { + let ans = unsafe { self.kind.AmountMissing }; + crate::error::PaymentError::AmountMissing { + err: ans.err.cst_decode(), + } + } + 5 => { + let ans = unsafe { self.kind.InvalidNetwork }; + crate::error::PaymentError::InvalidNetwork { + err: ans.err.cst_decode(), + } + } + 6 => { let ans = unsafe { self.kind.Generic }; crate::error::PaymentError::Generic { err: ans.err.cst_decode(), } } - 5 => crate::error::PaymentError::InvalidOrExpiredFees, - 6 => crate::error::PaymentError::InsufficientFunds, - 7 => { + 7 => crate::error::PaymentError::InvalidOrExpiredFees, + 8 => crate::error::PaymentError::InsufficientFunds, + 9 => { let ans = unsafe { self.kind.InvalidInvoice }; crate::error::PaymentError::InvalidInvoice { err: ans.err.cst_decode(), } } - 8 => crate::error::PaymentError::InvalidPreimage, - 9 => { + 10 => crate::error::PaymentError::InvalidPreimage, + 11 => { let ans = unsafe { self.kind.LwkError }; crate::error::PaymentError::LwkError { err: ans.err.cst_decode(), } } - 10 => crate::error::PaymentError::PairsNotFound, - 11 => crate::error::PaymentError::PaymentTimeout, - 12 => crate::error::PaymentError::PersistError, - 13 => { + 12 => crate::error::PaymentError::PairsNotFound, + 13 => crate::error::PaymentError::PaymentTimeout, + 14 => crate::error::PaymentError::PersistError, + 15 => { let ans = unsafe { self.kind.ReceiveError }; crate::error::PaymentError::ReceiveError { err: ans.err.cst_decode(), } } - 14 => { + 16 => { let ans = unsafe { self.kind.Refunded }; crate::error::PaymentError::Refunded { err: ans.err.cst_decode(), refund_tx_id: ans.refund_tx_id.cst_decode(), } } - 15 => crate::error::PaymentError::SelfTransferNotSupported, - 16 => { + 17 => crate::error::PaymentError::SelfTransferNotSupported, + 18 => { let ans = unsafe { self.kind.SendError }; crate::error::PaymentError::SendError { err: ans.err.cst_decode(), } } - 17 => { + 19 => { let ans = unsafe { self.kind.SignerError }; crate::error::PaymentError::SignerError { err: ans.err.cst_decode(), @@ -7896,43 +8064,20 @@ mod io { } } } - impl CstDecode - for wire_cst_prepare_receive_onchain_request - { + impl CstDecode for wire_cst_prepare_receive_request { // Codec=Cst (C-struct based), see doc to use other codecs - fn cst_decode(self) -> crate::model::PrepareReceiveOnchainRequest { - crate::model::PrepareReceiveOnchainRequest { + fn cst_decode(self) -> crate::model::PrepareReceiveRequest { + crate::model::PrepareReceiveRequest { payer_amount_sat: self.payer_amount_sat.cst_decode(), + payment_method: self.payment_method.cst_decode(), } } } - impl CstDecode - for wire_cst_prepare_receive_onchain_response - { + impl CstDecode for wire_cst_prepare_receive_response { // Codec=Cst (C-struct based), see doc to use other codecs - fn cst_decode(self) -> crate::model::PrepareReceiveOnchainResponse { - crate::model::PrepareReceiveOnchainResponse { - payer_amount_sat: self.payer_amount_sat.cst_decode(), - fees_sat: self.fees_sat.cst_decode(), - } - } - } - impl CstDecode - for wire_cst_prepare_receive_payment_request - { - // Codec=Cst (C-struct based), see doc to use other codecs - fn cst_decode(self) -> crate::model::PrepareReceivePaymentRequest { - crate::model::PrepareReceivePaymentRequest { - payer_amount_sat: self.payer_amount_sat.cst_decode(), - } - } - } - impl CstDecode - for wire_cst_prepare_receive_payment_response - { - // Codec=Cst (C-struct based), see doc to use other codecs - fn cst_decode(self) -> crate::model::PrepareReceivePaymentResponse { - crate::model::PrepareReceivePaymentResponse { + fn cst_decode(self) -> crate::model::PrepareReceiveResponse { + crate::model::PrepareReceiveResponse { + payment_method: self.payment_method.cst_decode(), payer_amount_sat: self.payer_amount_sat.cst_decode(), fees_sat: self.fees_sat.cst_decode(), } @@ -7962,7 +8107,8 @@ mod io { // Codec=Cst (C-struct based), see doc to use other codecs fn cst_decode(self) -> crate::model::PrepareSendRequest { crate::model::PrepareSendRequest { - invoice: self.invoice.cst_decode(), + destination: self.destination.cst_decode(), + amount_sat: self.amount_sat.cst_decode(), } } } @@ -7970,7 +8116,7 @@ mod io { // Codec=Cst (C-struct based), see doc to use other codecs fn cst_decode(self) -> crate::model::PrepareSendResponse { crate::model::PrepareSendResponse { - invoice: self.invoice.cst_decode(), + destination: self.destination.cst_decode(), fees_sat: self.fees_sat.cst_decode(), } } @@ -7984,21 +8130,12 @@ mod io { } } } - impl CstDecode for wire_cst_receive_onchain_response { - // Codec=Cst (C-struct based), see doc to use other codecs - fn cst_decode(self) -> crate::model::ReceiveOnchainResponse { - crate::model::ReceiveOnchainResponse { - address: self.address.cst_decode(), - bip21: self.bip21.cst_decode(), - } - } - } impl CstDecode for wire_cst_receive_payment_request { // Codec=Cst (C-struct based), see doc to use other codecs fn cst_decode(self) -> crate::model::ReceivePaymentRequest { crate::model::ReceivePaymentRequest { description: self.description.cst_decode(), - prepare_res: self.prepare_res.cst_decode(), + prepare_response: self.prepare_response.cst_decode(), } } } @@ -8006,8 +8143,7 @@ mod io { // Codec=Cst (C-struct based), see doc to use other codecs fn cst_decode(self) -> crate::model::ReceivePaymentResponse { crate::model::ReceivePaymentResponse { - id: self.id.cst_decode(), - invoice: self.invoice.cst_decode(), + destination: self.destination.cst_decode(), } } } @@ -8148,6 +8284,34 @@ mod io { } } } + impl CstDecode for wire_cst_send_destination { + // Codec=Cst (C-struct based), see doc to use other codecs + fn cst_decode(self) -> crate::model::SendDestination { + match self.tag { + 0 => { + let ans = unsafe { self.kind.LiquidAddress }; + crate::model::SendDestination::LiquidAddress { + address_data: ans.address_data.cst_decode(), + } + } + 1 => { + let ans = unsafe { self.kind.Bolt11 }; + crate::model::SendDestination::Bolt11 { + invoice: ans.invoice.cst_decode(), + } + } + _ => unreachable!(), + } + } + } + impl CstDecode for wire_cst_send_payment_request { + // Codec=Cst (C-struct based), see doc to use other codecs + fn cst_decode(self) -> crate::model::SendPaymentRequest { + crate::model::SendPaymentRequest { + prepare_response: self.prepare_response.cst_decode(), + } + } + } impl CstDecode for wire_cst_send_payment_response { // Codec=Cst (C-struct based), see doc to use other codecs fn cst_decode(self) -> crate::model::SendPaymentResponse { @@ -8272,7 +8436,7 @@ mod io { impl NewWithNullPtr for wire_cst_buy_bitcoin_request { fn new_with_null_ptr() -> Self { Self { - prepare_res: Default::default(), + prepare_response: Default::default(), redirect_url: core::ptr::null_mut(), } } @@ -8734,7 +8898,7 @@ mod io { fn new_with_null_ptr() -> Self { Self { address: core::ptr::null_mut(), - prepare_res: Default::default(), + prepare_response: Default::default(), } } } @@ -8746,18 +8910,14 @@ mod io { impl NewWithNullPtr for wire_cst_payment { fn new_with_null_ptr() -> Self { Self { + destination: core::ptr::null_mut(), tx_id: core::ptr::null_mut(), - swap_id: core::ptr::null_mut(), timestamp: Default::default(), amount_sat: Default::default(), fees_sat: Default::default(), - preimage: core::ptr::null_mut(), - bolt11: core::ptr::null_mut(), - description: core::ptr::null_mut(), - refund_tx_id: core::ptr::null_mut(), - refund_tx_amount_sat: core::ptr::null_mut(), payment_type: Default::default(), status: Default::default(), + details: core::ptr::null_mut(), } } } @@ -8766,6 +8926,19 @@ mod io { Self::new_with_null_ptr() } } + impl NewWithNullPtr for wire_cst_payment_details { + fn new_with_null_ptr() -> Self { + Self { + tag: -1, + kind: PaymentDetailsKind { nil__: () }, + } + } + } + impl Default for wire_cst_payment_details { + fn default() -> Self { + Self::new_with_null_ptr() + } + } impl NewWithNullPtr for wire_cst_payment_error { fn new_with_null_ptr() -> Self { Self { @@ -8833,52 +9006,29 @@ mod io { Self::new_with_null_ptr() } } - impl NewWithNullPtr for wire_cst_prepare_receive_onchain_request { + impl NewWithNullPtr for wire_cst_prepare_receive_request { fn new_with_null_ptr() -> Self { Self { - payer_amount_sat: Default::default(), + payer_amount_sat: core::ptr::null_mut(), + payment_method: Default::default(), } } } - impl Default for wire_cst_prepare_receive_onchain_request { + impl Default for wire_cst_prepare_receive_request { fn default() -> Self { Self::new_with_null_ptr() } } - impl NewWithNullPtr for wire_cst_prepare_receive_onchain_response { + impl NewWithNullPtr for wire_cst_prepare_receive_response { fn new_with_null_ptr() -> Self { Self { - payer_amount_sat: Default::default(), + payment_method: Default::default(), + payer_amount_sat: core::ptr::null_mut(), fees_sat: Default::default(), } } } - impl Default for wire_cst_prepare_receive_onchain_response { - fn default() -> Self { - Self::new_with_null_ptr() - } - } - impl NewWithNullPtr for wire_cst_prepare_receive_payment_request { - fn new_with_null_ptr() -> Self { - Self { - payer_amount_sat: Default::default(), - } - } - } - impl Default for wire_cst_prepare_receive_payment_request { - fn default() -> Self { - Self::new_with_null_ptr() - } - } - impl NewWithNullPtr for wire_cst_prepare_receive_payment_response { - fn new_with_null_ptr() -> Self { - Self { - payer_amount_sat: Default::default(), - fees_sat: Default::default(), - } - } - } - impl Default for wire_cst_prepare_receive_payment_response { + impl Default for wire_cst_prepare_receive_response { fn default() -> Self { Self::new_with_null_ptr() } @@ -8914,7 +9064,8 @@ mod io { impl NewWithNullPtr for wire_cst_prepare_send_request { fn new_with_null_ptr() -> Self { Self { - invoice: core::ptr::null_mut(), + destination: core::ptr::null_mut(), + amount_sat: core::ptr::null_mut(), } } } @@ -8926,7 +9077,7 @@ mod io { impl NewWithNullPtr for wire_cst_prepare_send_response { fn new_with_null_ptr() -> Self { Self { - invoice: core::ptr::null_mut(), + destination: Default::default(), fees_sat: Default::default(), } } @@ -8949,24 +9100,11 @@ mod io { Self::new_with_null_ptr() } } - impl NewWithNullPtr for wire_cst_receive_onchain_response { - fn new_with_null_ptr() -> Self { - Self { - address: core::ptr::null_mut(), - bip21: core::ptr::null_mut(), - } - } - } - impl Default for wire_cst_receive_onchain_response { - fn default() -> Self { - Self::new_with_null_ptr() - } - } impl NewWithNullPtr for wire_cst_receive_payment_request { fn new_with_null_ptr() -> Self { Self { description: core::ptr::null_mut(), - prepare_res: Default::default(), + prepare_response: Default::default(), } } } @@ -8978,8 +9116,7 @@ mod io { impl NewWithNullPtr for wire_cst_receive_payment_response { fn new_with_null_ptr() -> Self { Self { - id: core::ptr::null_mut(), - invoice: core::ptr::null_mut(), + destination: core::ptr::null_mut(), } } } @@ -9112,6 +9249,31 @@ mod io { Self::new_with_null_ptr() } } + impl NewWithNullPtr for wire_cst_send_destination { + fn new_with_null_ptr() -> Self { + Self { + tag: -1, + kind: SendDestinationKind { nil__: () }, + } + } + } + impl Default for wire_cst_send_destination { + fn default() -> Self { + Self::new_with_null_ptr() + } + } + impl NewWithNullPtr for wire_cst_send_payment_request { + fn new_with_null_ptr() -> Self { + Self { + prepare_response: Default::default(), + } + } + } + impl Default for wire_cst_send_payment_request { + fn default() -> Self { + Self::new_with_null_ptr() + } + } impl NewWithNullPtr for wire_cst_send_payment_response { fn new_with_null_ptr() -> Self { Self { @@ -9319,20 +9481,11 @@ mod io { wire__crate__bindings__BindingLiquidSdk_prepare_pay_onchain_impl(port_, that, req) } - #[no_mangle] - pub extern "C" fn frbgen_breez_liquid_wire__crate__bindings__BindingLiquidSdk_prepare_receive_onchain( - port_: i64, - that: usize, - req: *mut wire_cst_prepare_receive_onchain_request, - ) { - wire__crate__bindings__BindingLiquidSdk_prepare_receive_onchain_impl(port_, that, req) - } - #[no_mangle] pub extern "C" fn frbgen_breez_liquid_wire__crate__bindings__BindingLiquidSdk_prepare_receive_payment( port_: i64, that: usize, - req: *mut wire_cst_prepare_receive_payment_request, + req: *mut wire_cst_prepare_receive_request, ) { wire__crate__bindings__BindingLiquidSdk_prepare_receive_payment_impl(port_, that, req) } @@ -9355,15 +9508,6 @@ mod io { wire__crate__bindings__BindingLiquidSdk_prepare_send_payment_impl(port_, that, req) } - #[no_mangle] - pub extern "C" fn frbgen_breez_liquid_wire__crate__bindings__BindingLiquidSdk_receive_onchain( - port_: i64, - that: usize, - req: *mut wire_cst_prepare_receive_onchain_response, - ) { - wire__crate__bindings__BindingLiquidSdk_receive_onchain_impl(port_, that, req) - } - #[no_mangle] pub extern "C" fn frbgen_breez_liquid_wire__crate__bindings__BindingLiquidSdk_receive_payment( port_: i64, @@ -9410,7 +9554,7 @@ mod io { pub extern "C" fn frbgen_breez_liquid_wire__crate__bindings__BindingLiquidSdk_send_payment( port_: i64, that: usize, - req: *mut wire_cst_prepare_send_response, + req: *mut wire_cst_send_payment_request, ) { wire__crate__bindings__BindingLiquidSdk_send_payment_impl(port_, that, req) } @@ -9671,6 +9815,14 @@ mod io { flutter_rust_bridge::for_generated::new_leak_box_ptr(wire_cst_payment::new_with_null_ptr()) } + #[no_mangle] + pub extern "C" fn frbgen_breez_liquid_cst_new_box_autoadd_payment_details( + ) -> *mut wire_cst_payment_details { + flutter_rust_bridge::for_generated::new_leak_box_ptr( + wire_cst_payment_details::new_with_null_ptr(), + ) + } + #[no_mangle] pub extern "C" fn frbgen_breez_liquid_cst_new_box_autoadd_prepare_buy_bitcoin_request( ) -> *mut wire_cst_prepare_buy_bitcoin_request { @@ -9688,26 +9840,10 @@ mod io { } #[no_mangle] - pub extern "C" fn frbgen_breez_liquid_cst_new_box_autoadd_prepare_receive_onchain_request( - ) -> *mut wire_cst_prepare_receive_onchain_request { + pub extern "C" fn frbgen_breez_liquid_cst_new_box_autoadd_prepare_receive_request( + ) -> *mut wire_cst_prepare_receive_request { flutter_rust_bridge::for_generated::new_leak_box_ptr( - wire_cst_prepare_receive_onchain_request::new_with_null_ptr(), - ) - } - - #[no_mangle] - pub extern "C" fn frbgen_breez_liquid_cst_new_box_autoadd_prepare_receive_onchain_response( - ) -> *mut wire_cst_prepare_receive_onchain_response { - flutter_rust_bridge::for_generated::new_leak_box_ptr( - wire_cst_prepare_receive_onchain_response::new_with_null_ptr(), - ) - } - - #[no_mangle] - pub extern "C" fn frbgen_breez_liquid_cst_new_box_autoadd_prepare_receive_payment_request( - ) -> *mut wire_cst_prepare_receive_payment_request { - flutter_rust_bridge::for_generated::new_leak_box_ptr( - wire_cst_prepare_receive_payment_request::new_with_null_ptr(), + wire_cst_prepare_receive_request::new_with_null_ptr(), ) } @@ -9727,14 +9863,6 @@ mod io { ) } - #[no_mangle] - pub extern "C" fn frbgen_breez_liquid_cst_new_box_autoadd_prepare_send_response( - ) -> *mut wire_cst_prepare_send_response { - flutter_rust_bridge::for_generated::new_leak_box_ptr( - wire_cst_prepare_send_response::new_with_null_ptr(), - ) - } - #[no_mangle] pub extern "C" fn frbgen_breez_liquid_cst_new_box_autoadd_receive_payment_request( ) -> *mut wire_cst_receive_payment_request { @@ -9765,6 +9893,14 @@ mod io { flutter_rust_bridge::for_generated::new_leak_box_ptr(wire_cst_sdk_event::new_with_null_ptr()) } + #[no_mangle] + pub extern "C" fn frbgen_breez_liquid_cst_new_box_autoadd_send_payment_request( + ) -> *mut wire_cst_send_payment_request { + flutter_rust_bridge::for_generated::new_leak_box_ptr( + wire_cst_send_payment_request::new_with_null_ptr(), + ) + } + #[no_mangle] pub extern "C" fn frbgen_breez_liquid_cst_new_box_autoadd_success_action_processed( ) -> *mut wire_cst_success_action_processed { @@ -9979,7 +10115,7 @@ mod io { #[repr(C)] #[derive(Clone, Copy)] pub struct wire_cst_buy_bitcoin_request { - prepare_res: wire_cst_prepare_buy_bitcoin_response, + prepare_response: wire_cst_prepare_buy_bitcoin_response, redirect_url: *mut wire_cst_list_prim_u_8_strict, } #[repr(C)] @@ -10528,23 +10664,57 @@ mod io { #[derive(Clone, Copy)] pub struct wire_cst_pay_onchain_request { address: *mut wire_cst_list_prim_u_8_strict, - prepare_res: wire_cst_prepare_pay_onchain_response, + prepare_response: wire_cst_prepare_pay_onchain_response, } #[repr(C)] #[derive(Clone, Copy)] pub struct wire_cst_payment { + destination: *mut wire_cst_list_prim_u_8_strict, tx_id: *mut wire_cst_list_prim_u_8_strict, - swap_id: *mut wire_cst_list_prim_u_8_strict, timestamp: u32, amount_sat: u64, fees_sat: u64, + payment_type: i32, + status: i32, + details: *mut wire_cst_payment_details, + } + #[repr(C)] + #[derive(Clone, Copy)] + pub struct wire_cst_payment_details { + tag: i32, + kind: PaymentDetailsKind, + } + #[repr(C)] + #[derive(Clone, Copy)] + pub union PaymentDetailsKind { + Lightning: wire_cst_PaymentDetails_Lightning, + Liquid: wire_cst_PaymentDetails_Liquid, + Bitcoin: wire_cst_PaymentDetails_Bitcoin, + nil__: (), + } + #[repr(C)] + #[derive(Clone, Copy)] + pub struct wire_cst_PaymentDetails_Lightning { + swap_id: *mut wire_cst_list_prim_u_8_strict, + description: *mut wire_cst_list_prim_u_8_strict, preimage: *mut wire_cst_list_prim_u_8_strict, bolt11: *mut wire_cst_list_prim_u_8_strict, + refund_tx_id: *mut wire_cst_list_prim_u_8_strict, + refund_tx_amount_sat: *mut u64, + } + #[repr(C)] + #[derive(Clone, Copy)] + pub struct wire_cst_PaymentDetails_Liquid { + destination: *mut wire_cst_list_prim_u_8_strict, + description: *mut wire_cst_list_prim_u_8_strict, + } + #[repr(C)] + #[derive(Clone, Copy)] + pub struct wire_cst_PaymentDetails_Bitcoin { + swap_id: *mut wire_cst_list_prim_u_8_strict, description: *mut wire_cst_list_prim_u_8_strict, refund_tx_id: *mut wire_cst_list_prim_u_8_strict, refund_tx_amount_sat: *mut u64, - payment_type: i32, - status: i32, } #[repr(C)] #[derive(Clone, Copy)] @@ -10555,6 +10725,8 @@ mod io { #[repr(C)] #[derive(Clone, Copy)] pub union PaymentErrorKind { + AmountMissing: wire_cst_PaymentError_AmountMissing, + InvalidNetwork: wire_cst_PaymentError_InvalidNetwork, Generic: wire_cst_PaymentError_Generic, InvalidInvoice: wire_cst_PaymentError_InvalidInvoice, LwkError: wire_cst_PaymentError_LwkError, @@ -10566,6 +10738,16 @@ mod io { } #[repr(C)] #[derive(Clone, Copy)] + pub struct wire_cst_PaymentError_AmountMissing { + err: *mut wire_cst_list_prim_u_8_strict, + } + #[repr(C)] + #[derive(Clone, Copy)] + pub struct wire_cst_PaymentError_InvalidNetwork { + err: *mut wire_cst_list_prim_u_8_strict, + } + #[repr(C)] + #[derive(Clone, Copy)] pub struct wire_cst_PaymentError_Generic { err: *mut wire_cst_list_prim_u_8_strict, } @@ -10628,24 +10810,15 @@ mod io { } #[repr(C)] #[derive(Clone, Copy)] - pub struct wire_cst_prepare_receive_onchain_request { - payer_amount_sat: u64, + pub struct wire_cst_prepare_receive_request { + payer_amount_sat: *mut u64, + payment_method: i32, } #[repr(C)] #[derive(Clone, Copy)] - pub struct wire_cst_prepare_receive_onchain_response { - payer_amount_sat: u64, - fees_sat: u64, - } - #[repr(C)] - #[derive(Clone, Copy)] - pub struct wire_cst_prepare_receive_payment_request { - payer_amount_sat: u64, - } - #[repr(C)] - #[derive(Clone, Copy)] - pub struct wire_cst_prepare_receive_payment_response { - payer_amount_sat: u64, + pub struct wire_cst_prepare_receive_response { + payment_method: i32, + payer_amount_sat: *mut u64, fees_sat: u64, } #[repr(C)] @@ -10665,12 +10838,13 @@ mod io { #[repr(C)] #[derive(Clone, Copy)] pub struct wire_cst_prepare_send_request { - invoice: *mut wire_cst_list_prim_u_8_strict, + destination: *mut wire_cst_list_prim_u_8_strict, + amount_sat: *mut u64, } #[repr(C)] #[derive(Clone, Copy)] pub struct wire_cst_prepare_send_response { - invoice: *mut wire_cst_list_prim_u_8_strict, + destination: wire_cst_send_destination, fees_sat: u64, } #[repr(C)] @@ -10681,21 +10855,14 @@ mod io { } #[repr(C)] #[derive(Clone, Copy)] - pub struct wire_cst_receive_onchain_response { - address: *mut wire_cst_list_prim_u_8_strict, - bip21: *mut wire_cst_list_prim_u_8_strict, - } - #[repr(C)] - #[derive(Clone, Copy)] pub struct wire_cst_receive_payment_request { description: *mut wire_cst_list_prim_u_8_strict, - prepare_res: wire_cst_prepare_receive_payment_response, + prepare_response: wire_cst_prepare_receive_response, } #[repr(C)] #[derive(Clone, Copy)] pub struct wire_cst_receive_payment_response { - id: *mut wire_cst_list_prim_u_8_strict, - invoice: *mut wire_cst_list_prim_u_8_strict, + destination: *mut wire_cst_list_prim_u_8_strict, } #[repr(C)] #[derive(Clone, Copy)] @@ -10818,6 +10985,34 @@ mod io { } #[repr(C)] #[derive(Clone, Copy)] + pub struct wire_cst_send_destination { + tag: i32, + kind: SendDestinationKind, + } + #[repr(C)] + #[derive(Clone, Copy)] + pub union SendDestinationKind { + LiquidAddress: wire_cst_SendDestination_LiquidAddress, + Bolt11: wire_cst_SendDestination_Bolt11, + nil__: (), + } + #[repr(C)] + #[derive(Clone, Copy)] + pub struct wire_cst_SendDestination_LiquidAddress { + address_data: *mut wire_cst_liquid_address_data, + } + #[repr(C)] + #[derive(Clone, Copy)] + pub struct wire_cst_SendDestination_Bolt11 { + invoice: *mut wire_cst_ln_invoice, + } + #[repr(C)] + #[derive(Clone, Copy)] + pub struct wire_cst_send_payment_request { + prepare_response: wire_cst_prepare_send_response, + } + #[repr(C)] + #[derive(Clone, Copy)] pub struct wire_cst_send_payment_response { payment: wire_cst_payment, } diff --git a/lib/core/src/lib.rs b/lib/core/src/lib.rs index 5b2a4b1..6531f17 100644 --- a/lib/core/src/lib.rs +++ b/lib/core/src/lib.rs @@ -45,32 +45,39 @@ //! //! // Set the amount you wish the payer to send, which should be within the above limits //! let prepare_receive_response = sdk -//! .prepare_receive_payment(&PrepareReceivePaymentRequest { -//! payer_amount_sat: 5_000, +//! .prepare_receive_payment(&PrepareReceiveRequest { +//! payment_method: PaymentMethod::Lightning, +//! payer_amount_sat: Some(5_000), //! }) //! .await?; //! //! // If the fees are acceptable, continue to create the Receive Payment //! let receive_fees_sat = prepare_receive_response.fees_sat; //! -//! let receive_payment_response = sdk.receive_payment(&prepare_receive_response).await?; +//! let receive_payment_response = sdk.receive_payment(&ReceivePaymentRequest { +//! description: Some("my description".to_string()), +//! prepare_response: receive_payment_response, +//! }).await?; //! -//! let invoice = receive_payment_response.invoice; +//! let destination = receive_payment_response.destination; //! ``` //! //! or make payments //! ```ignore -//! // Set the BOLT11 invoice you wish to pay +//! // Set the BOLT11 invoice or Liquid BIP21/address you wish to pay //! let prepare_send_response = sdk //! .prepare_send_payment(&PrepareSendRequest { -//! invoice: "...".to_string(), +//! destination: "invoice or Liquid BIP21/address".to_string(), +//! amount_sat: Some(3_000), //! }) //! .await?; //! //! // If the fees are acceptable, continue to create the Send Payment //! let send_fees_sat = prepare_send_response.fees_sat; //! -//! let send_response = sdk.send_payment(&prepare_send_response).await?; +//! let send_response = sdk.send_payment(&SendPayentRequest { +//! prepare_response: prepare_send_response, +//! }).await?; //! let payment = send_response.payment; //! ``` //! @@ -108,20 +115,18 @@ //! * [sdk::LiquidSdk::prepare_send_payment] to check fees //! * [sdk::LiquidSdk::send_payment] to pay an invoice //! -//! ### Receiving a Lightning payment +//! ### Receiving a Lightning/onchain payment //! //! * [sdk::LiquidSdk::prepare_receive_payment] to check fees -//! * [sdk::LiquidSdk::receive_payment] to generate an invoice +//! * [sdk::LiquidSdk::receive_payment] to generate an invoice/Liquid BIP21/Liquid address //! //! ### Sending an onchain payment //! //! * [sdk::LiquidSdk::prepare_pay_onchain] to check fees //! * [sdk::LiquidSdk::pay_onchain] to pay to a Bitcoin address //! -//! ### Receiving an onchain payment +//! ### Refunding a payment //! -//! * [sdk::LiquidSdk::prepare_receive_onchain] to check fees -//! * [sdk::LiquidSdk::receive_onchain] to generate a Bitcoin address //! * [sdk::LiquidSdk::list_refundables] to get a list of refundable swaps //! * [sdk::LiquidSdk::prepare_refund] to check the refund fees //! * [sdk::LiquidSdk::refund] to broadcast a refund transaction diff --git a/lib/core/src/model.rs b/lib/core/src/model.rs index 42eeae1..371efb1 100644 --- a/lib/core/src/model.rs +++ b/lib/core/src/model.rs @@ -25,8 +25,9 @@ use crate::receive_swap::{ }; use crate::utils; -pub const STANDARD_FEE_RATE_SAT_PER_VBYTE: f32 = 0.1; -pub const LOWBALL_FEE_RATE_SAT_PER_VBYTE: f32 = 0.01; +// Both use f64 for the maximum precision when converting between units +pub const STANDARD_FEE_RATE_SAT_PER_VBYTE: f64 = 0.1; +pub const LOWBALL_FEE_RATE_SAT_PER_VBYTE: f64 = 0.01; /// Configuration for the Liquid SDK #[derive(Clone, Debug, Serialize)] @@ -95,7 +96,7 @@ impl Config { .unwrap_or(DEFAULT_ZERO_CONF_MAX_SAT) } - pub(crate) fn lowball_fee_rate_msat_per_vbyte(&self) -> Option { + pub(crate) fn lowball_fee_rate_msat_per_vbyte(&self) -> Option { match self.network { LiquidNetwork::Mainnet => Some(LOWBALL_FEE_RATE_SAT_PER_VBYTE * 1000.0), LiquidNetwork::Testnet => None, @@ -194,16 +195,29 @@ pub struct ConnectRequest { pub config: Config, } +/// The send/receive methods supported by the SDK +#[derive(Clone, Debug, EnumString, Serialize, Eq, PartialEq)] +pub enum PaymentMethod { + #[strum(serialize = "lightning")] + Lightning, + #[strum(serialize = "bitcoin")] + BitcoinAddress, + #[strum(serialize = "liquid")] + LiquidAddress, +} + /// An argument when calling [crate::sdk::LiquidSdk::prepare_receive_payment]. #[derive(Debug, Serialize)] -pub struct PrepareReceivePaymentRequest { - pub payer_amount_sat: u64, +pub struct PrepareReceiveRequest { + pub payer_amount_sat: Option, + pub payment_method: PaymentMethod, } /// Returned when calling [crate::sdk::LiquidSdk::prepare_receive_payment]. #[derive(Debug, Serialize)] -pub struct PrepareReceivePaymentResponse { - pub payer_amount_sat: u64, +pub struct PrepareReceiveResponse { + pub payment_method: PaymentMethod, + pub payer_amount_sat: Option, pub fees_sat: u64, } @@ -211,14 +225,15 @@ pub struct PrepareReceivePaymentResponse { #[derive(Debug, Serialize)] pub struct ReceivePaymentRequest { pub description: Option, - pub prepare_res: PrepareReceivePaymentResponse, + pub prepare_response: PrepareReceiveResponse, } /// Returned when calling [crate::sdk::LiquidSdk::receive_payment]. #[derive(Debug, Serialize)] pub struct ReceivePaymentResponse { - pub id: String, - pub invoice: String, + /// Either a BIP21 URI (Liquid or Bitcoin), a Liquid address + /// or an invoice, depending on the [PrepareReceivePaymentResponse] parameters + pub destination: String, } /// The minimum and maximum in satoshis of a Lightning or onchain payment. @@ -250,16 +265,39 @@ pub struct OnchainPaymentLimitsResponse { /// An argument when calling [crate::sdk::LiquidSdk::prepare_send_payment]. #[derive(Debug, Serialize, Clone)] pub struct PrepareSendRequest { - pub invoice: String, + /// The destination we intend to pay to. + /// Supports BIP21 URIs, BOLT11 invoices and Liquid addresses + pub destination: String, + + /// Should only be set when paying directly onchain or to a BIP21 URI + /// where no amount is specified + pub amount_sat: Option, +} + +/// Specifies the supported destinations which can be payed by the SDK +#[derive(Clone, Debug, Serialize)] +pub enum SendDestination { + LiquidAddress { + address_data: liquid::LiquidAddressData, + }, + Bolt11 { + invoice: LNInvoice, + }, } /// Returned when calling [crate::sdk::LiquidSdk::prepare_send_payment]. #[derive(Debug, Serialize, Clone)] pub struct PrepareSendResponse { - pub invoice: String, + pub destination: SendDestination, pub fees_sat: u64, } +/// An argument when calling [crate::sdk::LiquidSdk::send_payment]. +#[derive(Debug, Serialize)] +pub struct SendPaymentRequest { + pub prepare_response: PrepareSendResponse, +} + /// Returned when calling [crate::sdk::LiquidSdk::send_payment]. #[derive(Debug, Serialize)] pub struct SendPaymentResponse { @@ -285,27 +323,7 @@ pub struct PreparePayOnchainResponse { #[derive(Debug, Serialize)] pub struct PayOnchainRequest { pub address: String, - pub prepare_res: PreparePayOnchainResponse, -} - -/// An argument when calling [crate::sdk::LiquidSdk::prepare_receive_onchain]. -#[derive(Debug, Serialize, Clone)] -pub struct PrepareReceiveOnchainRequest { - pub payer_amount_sat: u64, -} - -/// Returned when calling [crate::sdk::LiquidSdk::prepare_receive_onchain]. -#[derive(Debug, Serialize, Clone)] -pub struct PrepareReceiveOnchainResponse { - pub payer_amount_sat: u64, - pub fees_sat: u64, -} - -/// Returned when calling [crate::sdk::LiquidSdk::receive_onchain]. -#[derive(Debug, Serialize)] -pub struct ReceiveOnchainResponse { - pub address: String, - pub bip21: String, + pub prepare_response: PreparePayOnchainResponse, } /// An argument when calling [crate::sdk::LiquidSdk::prepare_refund]. @@ -929,10 +947,19 @@ pub struct PaymentTxData { pub is_confirmed: bool, } +#[derive(Debug, Clone, Serialize)] +pub enum PaymentSwapType { + Receive, + Send, + Chain, +} + #[derive(Debug, Clone, Serialize)] pub struct PaymentSwapData { pub swap_id: String, + pub swap_type: PaymentSwapType, + /// Swap creation timestamp pub created_at: u32, @@ -951,19 +978,97 @@ pub struct PaymentSwapData { pub refund_tx_id: Option, pub refund_tx_amount_sat: Option, + /// Present only for chain swaps. + /// In case of an outgoing chain swap, it's the Bitcoin address which will receive the funds + /// In case of an incoming chain swap, it's the Liquid address which will receive the funds + pub claim_address: Option, + /// Payment status derived from the swap status pub status: PaymentState, } +/// The specific details of a payment, depending on its type +#[derive(Debug, Clone, PartialEq, Serialize)] +pub enum PaymentDetails { + /// Swapping to or from Lightning + Lightning { + swap_id: String, + + /// Represents the invoice description + description: String, + + /// In case of a Send swap, this is the preimage of the paid invoice (proof of payment). + preimage: Option, + + /// Represents the invoice associated with a payment + /// In the case of a Send payment, this is the invoice paid by the swapper + /// In the case of a Receive payment, this is the invoice paid by the user + bolt11: Option, + + /// For a Send swap which was refunded, this is the refund tx id + refund_tx_id: Option, + + /// For a Send swap which was refunded, this is the refund amount + refund_tx_amount_sat: Option, + }, + /// Direct onchain payment to a Liquid address + Liquid { + /// Represents either a Liquid BIP21 URI or pure address + destination: String, + + /// Represents the BIP21 `message` field + description: String, + }, + /// Swapping to or from the Bitcoin chain + Bitcoin { + swap_id: String, + + /// Represents the invoice description + description: String, + + /// For a Send swap which was refunded, this is the refund tx id + refund_tx_id: Option, + + /// For a Send swap which was refunded, this is the refund amount + refund_tx_amount_sat: Option, + }, +} + +impl PaymentDetails { + pub(crate) fn get_swap_id(&self) -> Option { + match self { + Self::Lightning { swap_id, .. } | Self::Bitcoin { swap_id, .. } => { + Some(swap_id.clone()) + } + Self::Liquid { .. } => None, + } + } + + pub(crate) fn get_refund_tx_amount_sat(&self) -> Option { + match self { + Self::Lightning { + refund_tx_amount_sat, + .. + } + | Self::Bitcoin { + refund_tx_amount_sat, + .. + } => *refund_tx_amount_sat, + Self::Liquid { .. } => None, + } + } +} + /// Represents an SDK payment. /// /// By default, this is an onchain tx. It may represent a swap, if swap metadata is available. #[derive(Debug, Clone, PartialEq, Serialize)] pub struct Payment { - pub tx_id: Option, + /// The destination associated with the payment, if it was created via our SDK. + /// Can be either a Liquid/Bitcoin address, a Liquid BIP21 URI or an invoice + pub destination: Option, - /// The swap ID, if any swap is associated with this payment - pub swap_id: Option, + pub tx_id: Option, /// Composite timestamp that can be used for sorting or displaying the payment. /// @@ -992,23 +1097,6 @@ pub struct Payment { /// - for Receive payments, this is zero pub fees_sat: u64, - /// In case of a Send swap, this is the preimage of the paid invoice (proof of payment). - pub preimage: Option, - - /// Represents the invoice associated with a payment - /// In the case of a Send payment, this is the invoice paid by the swapper - /// In the case of a Receive payment, this is the invoice paid by the user - pub bolt11: Option, - - /// Represents the invoice description - pub description: String, - - /// For a Send swap which was refunded, this is the refund tx id - pub refund_tx_id: Option, - - /// For a Send swap which was refunded, this is the refund amount - pub refund_tx_amount_sat: Option, - /// If it is a `Send` or `Receive` payment pub payment_type: PaymentType, @@ -1018,6 +1106,10 @@ pub struct Payment { /// /// If the tx has an associated swap, this is determined by the swap status (pending or complete). pub status: PaymentState, + + /// The details of a payment, depending on its [destination](Payment::destination) and + /// [type](Payment::payment_type) + pub details: Option, } impl Payment { pub(crate) fn from_pending_swap(swap: PaymentSwapData, payment_type: PaymentType) -> Payment { @@ -1027,25 +1119,58 @@ impl Payment { }; Payment { + destination: swap.bolt11.clone(), tx_id: None, - swap_id: Some(swap.swap_id), timestamp: swap.created_at, amount_sat, fees_sat: swap.payer_amount_sat - swap.receiver_amount_sat, - preimage: swap.preimage, - bolt11: swap.bolt11, - description: swap.description, - refund_tx_id: swap.refund_tx_id, - refund_tx_amount_sat: swap.refund_tx_amount_sat, payment_type, status: swap.status, + details: Some(PaymentDetails::Lightning { + swap_id: swap.swap_id, + preimage: swap.preimage, + bolt11: swap.bolt11, + description: swap.description, + refund_tx_id: swap.refund_tx_id, + refund_tx_amount_sat: swap.refund_tx_amount_sat, + }), } } - pub(crate) fn from_tx_data(tx: PaymentTxData, swap: Option) -> Payment { + pub(crate) fn from_tx_data( + tx: PaymentTxData, + swap: Option, + payment_details: Option, + ) -> Payment { + let description = swap.as_ref().map(|s| s.description.clone()); Payment { tx_id: Some(tx.tx_id), - swap_id: swap.as_ref().map(|s| s.swap_id.clone()), + // When the swap is present and of type send and receive, we retrieve the destination from the invoice. + // If it's a chain swap instead, we use the `claim_address` field from the swap data (either pure Bitcoin or Liquid address). + // Otherwise, we specify the Liquid address (BIP21 or pure), set in `payment_details.address`. + destination: match &swap { + Some( + PaymentSwapData { + swap_type: PaymentSwapType::Receive, + bolt11, + .. + } + | PaymentSwapData { + swap_type: PaymentSwapType::Send, + bolt11, + .. + }, + ) => bolt11.clone(), + Some(PaymentSwapData { + swap_type: PaymentSwapType::Chain, + claim_address, + .. + }) => claim_address.clone(), + _ => match &payment_details { + Some(PaymentDetails::Liquid { destination, .. }) => Some(destination.clone()), + _ => None, + }, + }, timestamp: match swap { Some(ref swap) => swap.created_at, None => tx.timestamp.unwrap_or(utils::now()), @@ -1058,22 +1183,56 @@ impl Payment { PaymentType::Send => tx.fees_sat, }, }, - preimage: swap.as_ref().and_then(|s| s.preimage.clone()), - bolt11: swap.as_ref().and_then(|s| s.bolt11.clone()), - description: swap - .as_ref() - .map(|s| s.description.clone()) - .unwrap_or("Liquid transfer".to_string()), - refund_tx_id: swap.as_ref().and_then(|s| s.refund_tx_id.clone()), - refund_tx_amount_sat: swap.as_ref().and_then(|s| s.refund_tx_amount_sat), payment_type: tx.payment_type, - status: match swap { + status: match &swap { Some(swap) => swap.status, None => match tx.is_confirmed { true => PaymentState::Complete, false => PaymentState::Pending, }, }, + details: match swap { + Some( + PaymentSwapData { + swap_type: PaymentSwapType::Receive, + swap_id, + bolt11, + refund_tx_id, + preimage, + refund_tx_amount_sat, + .. + } + | PaymentSwapData { + swap_type: PaymentSwapType::Send, + swap_id, + bolt11, + preimage, + refund_tx_id, + refund_tx_amount_sat, + .. + }, + ) => Some(PaymentDetails::Lightning { + swap_id, + preimage, + bolt11, + refund_tx_id, + refund_tx_amount_sat, + description: description.unwrap_or("Liquid transfer".to_string()), + }), + Some(PaymentSwapData { + swap_type: PaymentSwapType::Chain, + swap_id, + refund_tx_id, + refund_tx_amount_sat, + .. + }) => Some(PaymentDetails::Bitcoin { + swap_id, + refund_tx_id, + refund_tx_amount_sat, + description: description.unwrap_or("Bitcoin transfer".to_string()), + }), + _ => payment_details, + }, } } } @@ -1114,7 +1273,7 @@ pub struct PrepareBuyBitcoinResponse { /// An argument when calling [crate::sdk::LiquidSdk::buy_bitcoin]. #[derive(Clone, Debug, Serialize)] pub struct BuyBitcoinRequest { - pub prepare_res: PrepareBuyBitcoinResponse, + pub prepare_response: PrepareBuyBitcoinResponse, /// The optional URL to redirect to after completing the buy. /// @@ -1185,6 +1344,7 @@ impl From for InternalSwapTree { /// * `PayError` indicates that an error occurred while trying to pay the invoice from the LNURL endpoint. /// This includes the payment hash of the failed invoice and the failure reason. #[derive(Serialize)] +#[allow(clippy::large_enum_variant)] pub enum LnUrlPayResult { EndpointSuccess { data: LnUrlPaySuccessData }, EndpointError { data: LnUrlErrorData }, diff --git a/lib/core/src/persist/migrations.rs b/lib/core/src/persist/migrations.rs index 2ca6605..34b2169 100644 --- a/lib/core/src/persist/migrations.rs +++ b/lib/core/src/persist/migrations.rs @@ -65,5 +65,10 @@ pub(crate) fn current_migrations() -> Vec<&'static str> { ALTER TABLE send_swaps ADD COLUMN description TEXT; ALTER TABLE chain_swaps ADD COLUMN description TEXT; ", + "CREATE TABLE IF NOT EXISTS payment_details ( + tx_id TEXT NOT NULL PRIMARY KEY, + destination TEXT NOT NULL, + description TEXT NOT NULL + );", ] } diff --git a/lib/core/src/persist/mod.rs b/lib/core/src/persist/mod.rs index db05dce..08b235f 100644 --- a/lib/core/src/persist/mod.rs +++ b/lib/core/src/persist/mod.rs @@ -83,7 +83,11 @@ impl Persister { } } - pub(crate) fn insert_or_update_payment(&self, ptx: PaymentTxData) -> Result<()> { + pub(crate) fn insert_or_update_payment( + &self, + ptx: PaymentTxData, + details: Option, + ) -> Result<()> { let mut con = self.get_connection()?; let tx = con.transaction()?; @@ -99,7 +103,7 @@ impl Persister { VALUES (?, ?, ?, ?, ?, ?) ", ( - ptx.tx_id, + &ptx.tx_id, ptx.timestamp, ptx.amount_sat, ptx.fees_sat, @@ -107,6 +111,22 @@ impl Persister { ptx.is_confirmed, ), )?; + if let Some(PaymentDetails::Liquid { + destination, + description, + }) = details + { + tx.execute( + "INSERT OR REPLACE INTO payment_details ( + tx_id, + destination, + description + ) + VALUES (?, ?, ?) + ", + (ptx.tx_id, destination, description), + )?; + } tx.commit()?; Ok(()) @@ -176,8 +196,11 @@ impl Persister { cs.refund_tx_id, cs.payer_amount_sat, cs.receiver_amount_sat, + cs.claim_address, cs.state, - rtx.amount_sat + rtx.amount_sat, + pd.destination, + pd.description FROM payment_tx_data AS ptx -- Payment tx (each tx results in a Payment) FULL JOIN ( SELECT * FROM receive_swaps @@ -190,6 +213,8 @@ impl Persister { ON ptx.tx_id in (cs.user_lockup_tx_id, cs.claim_tx_id) LEFT JOIN payment_tx_data AS rtx -- Refund tx data ON rtx.tx_id in (ss.refund_tx_id, cs.refund_tx_id) + LEFT JOIN payment_details AS pd -- Payment details + ON pd.tx_id = ptx.tx_id WHERE -- Filter out refund txs from Send Swaps ptx.tx_id NOT IN (SELECT refund_tx_id FROM send_swaps WHERE refund_tx_id NOT NULL) AND -- Filter out refund txs from Chain Swaps @@ -246,14 +271,19 @@ impl Persister { let maybe_chain_swap_refund_tx_id: Option = row.get(27)?; let maybe_chain_swap_payer_amount_sat: Option = row.get(28)?; let maybe_chain_swap_receiver_amount_sat: Option = row.get(29)?; - let maybe_chain_swap_state: Option = row.get(30)?; + let maybe_chain_swap_claim_address: Option = row.get(30)?; + let maybe_chain_swap_state: Option = row.get(31)?; - let maybe_swap_refund_tx_amount_sat: Option = row.get(31)?; + let maybe_swap_refund_tx_amount_sat: Option = row.get(32)?; + + let maybe_payment_details_destination: Option = row.get(33)?; + let maybe_payment_details_description: Option = row.get(34)?; let (swap, payment_type) = match maybe_receive_swap_id { Some(receive_swap_id) => ( Some(PaymentSwapData { swap_id: receive_swap_id, + swap_type: PaymentSwapType::Receive, created_at: maybe_receive_swap_created_at.unwrap_or(utils::now()), preimage: None, bolt11: maybe_receive_swap_invoice.clone(), @@ -266,6 +296,7 @@ impl Persister { receiver_amount_sat: maybe_receive_swap_receiver_amount_sat.unwrap_or(0), refund_tx_id: None, refund_tx_amount_sat: None, + claim_address: None, status: maybe_receive_swap_receiver_state.unwrap_or(PaymentState::Created), }), PaymentType::Receive, @@ -274,6 +305,7 @@ impl Persister { Some(send_swap_id) => ( Some(PaymentSwapData { swap_id: send_swap_id, + swap_type: PaymentSwapType::Send, created_at: maybe_send_swap_created_at.unwrap_or(utils::now()), preimage: maybe_send_swap_preimage, bolt11: maybe_send_swap_invoice.clone(), @@ -286,6 +318,7 @@ impl Persister { receiver_amount_sat: maybe_send_swap_receiver_amount_sat.unwrap_or(0), refund_tx_id: maybe_send_swap_refund_tx_id, refund_tx_amount_sat: maybe_swap_refund_tx_amount_sat, + claim_address: None, status: maybe_send_swap_state.unwrap_or(PaymentState::Created), }), PaymentType::Send, @@ -294,6 +327,7 @@ impl Persister { Some(chain_swap_id) => ( Some(PaymentSwapData { swap_id: chain_swap_id, + swap_type: PaymentSwapType::Chain, created_at: maybe_chain_swap_created_at.unwrap_or(utils::now()), preimage: maybe_chain_swap_preimage, bolt11: None, @@ -303,6 +337,7 @@ impl Persister { receiver_amount_sat: maybe_chain_swap_receiver_amount_sat.unwrap_or(0), refund_tx_id: maybe_chain_swap_refund_tx_id, refund_tx_amount_sat: maybe_swap_refund_tx_amount_sat, + claim_address: maybe_chain_swap_claim_address, status: maybe_chain_swap_state.unwrap_or(PaymentState::Created), }), maybe_chain_swap_direction @@ -314,11 +349,18 @@ impl Persister { }, }; + let payment_details = + maybe_payment_details_destination.map(|destination| PaymentDetails::Liquid { + destination, + description: maybe_payment_details_description + .unwrap_or("Liquid transfer".to_string()), + }); + match (tx, swap.clone()) { (None, None) => Err(maybe_tx_tx_id.err().unwrap()), (None, Some(swap)) => Ok(Payment::from_pending_swap(swap, payment_type)), - (Some(tx), None) => Ok(Payment::from_tx_data(tx, None)), - (Some(tx), Some(swap)) => Ok(Payment::from_tx_data(tx, Some(swap))), + (Some(tx), None) => Ok(Payment::from_tx_data(tx, None, payment_details)), + (Some(tx), Some(swap)) => Ok(Payment::from_tx_data(tx, Some(swap), payment_details)), } } @@ -413,7 +455,7 @@ mod tests { let (_temp_dir, storage) = new_persister()?; let payment_tx_data = new_payment_tx_data(PaymentType::Send); - storage.insert_or_update_payment(payment_tx_data.clone())?; + storage.insert_or_update_payment(payment_tx_data.clone(), None)?; assert!(storage .get_payments(&ListPaymentsRequest { diff --git a/lib/core/src/receive_swap.rs b/lib/core/src/receive_swap.rs index 0cc7e84..f32daa7 100644 --- a/lib/core/src/receive_swap.rs +++ b/lib/core/src/receive_swap.rs @@ -256,14 +256,17 @@ impl ReceiveSwapStateHandler { // We insert a pseudo-claim-tx in case LWK fails to pick up the new mempool tx for a while // This makes the tx known to the SDK (get_info, list_payments) instantly - self.persister.insert_or_update_payment(PaymentTxData { - tx_id: claim_tx_id.clone(), - timestamp: Some(utils::now()), - amount_sat: ongoing_receive_swap.receiver_amount_sat, - fees_sat: 0, - payment_type: PaymentType::Receive, - is_confirmed: false, - })?; + self.persister.insert_or_update_payment( + PaymentTxData { + tx_id: claim_tx_id.clone(), + timestamp: Some(utils::now()), + amount_sat: ongoing_receive_swap.receiver_amount_sat, + fees_sat: 0, + payment_type: PaymentType::Receive, + is_confirmed: false, + }, + None, + )?; self.update_swap_info(swap_id, Pending, Some(&claim_tx_id), None) .await?; diff --git a/lib/core/src/sdk.rs b/lib/core/src/sdk.rs index 45bb2b6..a4d1c0d 100644 --- a/lib/core/src/sdk.rs +++ b/lib/core/src/sdk.rs @@ -14,12 +14,13 @@ use futures_util::stream::select_all; use futures_util::StreamExt; use log::{debug, error, info}; use lwk_wollet::bitcoin::hex::DisplayHex; +use lwk_wollet::elements::AssetId; use lwk_wollet::hashes::{sha256, Hash}; use lwk_wollet::secp256k1::ThirtyTwoByteHash; use lwk_wollet::{elements, ElementsNetwork}; use sdk_common::bitcoin::secp256k1::Secp256k1; use sdk_common::bitcoin::util::bip32::ChildNumber; -use sdk_common::ensure_sdk; +use sdk_common::liquid::LiquidAddressData; use sdk_common::prelude::{FiatAPI, FiatCurrency, LnUrlPayError, LnUrlWithdrawError, Rate}; use tokio::sync::{watch, Mutex, RwLock}; use tokio::time::MissedTickBehavior; @@ -28,6 +29,7 @@ use url::Url; use crate::chain::bitcoin::BitcoinChainService; use crate::chain_swap::ChainSwapStateHandler; +use crate::ensure_sdk; use crate::error::SdkError; use crate::lightning_invoice::{Bolt11Invoice, Bolt11InvoiceDescription}; use crate::model::PaymentState::*; @@ -447,8 +449,12 @@ impl LiquidSdk { .await? } Pending => { + let Some(details) = &payment.details else { + return Err(anyhow::anyhow!("No payment details found")); + }; + // The swap state has changed to Pending - match payment.swap_id.clone() { + match details.get_swap_id() { Some(swap_id) => match self.persister.fetch_swap_by_id(&swap_id)? { Swap::Chain(ChainSwap { claim_tx_id, .. }) | Swap::Receive(ReceiveSwap { claim_tx_id, .. }) => { @@ -537,9 +543,12 @@ impl LiquidSdk { Complete => confirmed_sent_sat += p.amount_sat, Failed => { confirmed_sent_sat += p.amount_sat; - confirmed_received_sat += p.refund_tx_amount_sat.unwrap_or_default(); + if let Some(details) = p.details { + confirmed_received_sat += + details.get_refund_tx_amount_sat().unwrap_or_default(); + } } - Pending => match p.refund_tx_amount_sat { + Pending => match p.details.and_then(|d| d.get_refund_tx_amount_sat()) { Some(refund_tx_amount_sat) => { confirmed_sent_sat += p.amount_sat; pending_receive_sat += refund_tx_amount_sat; @@ -576,7 +585,7 @@ impl LiquidSdk { ("bitcoin", LiquidNetwork::Mainnet) => {} ("testnet", LiquidNetwork::Testnet) => {} _ => { - return Err(PaymentError::InvalidInvoice { + return Err(PaymentError::InvalidNetwork { err: "Invoice cannot be paid on the current network".to_string(), }) } @@ -659,7 +668,9 @@ impl LiquidSdk { self.estimate_onchain_tx_fee( amount_sat, temp_p2tr_addr, - self.config.lowball_fee_rate_msat_per_vbyte(), + self.config + .lowball_fee_rate_msat_per_vbyte() + .map(|v| v as f32), ) .await } @@ -669,30 +680,92 @@ impl LiquidSdk { /// # Arguments /// /// * `req` - the [PrepareSendRequest] containing: - /// * `invoice` - the bolt11 Lightning invoice to pay + /// * `destination` - Either a Liquid BIP21 URI/address or a BOLT11 invoice + /// * `amount_sat` - Should only be specified when paying directly onchain or via amount-less BIP21 + /// + /// # Returns + /// Returns a [PrepareSendResponse] containing: + /// * `destination` - the parsed destination, of type [SendDestination] + /// * `fees_sat` - the additional fees which will be paid by the sender pub async fn prepare_send_payment( &self, req: &PrepareSendRequest, ) -> Result { self.ensure_is_started().await?; - self.ensure_send_is_not_self_transfer(&req.invoice)?; - let invoice = self.validate_invoice(&req.invoice)?; + let fees_sat; + let receiver_amount_sat; + let payment_destination; - let receiver_amount_sat = invoice - .amount_milli_satoshis() - .ok_or(PaymentError::AmountOutOfRange)? - / 1000; - let lbtc_pair = self.validate_submarine_pairs(receiver_amount_sat)?; + match sdk_common::input_parser::parse(&req.destination).await? { + InputType::LiquidAddress { + address: mut liquid_address_data, + } => { + let Some(amount_sat) = liquid_address_data.amount_sat else { + return Err(PaymentError::AmountMissing { err: "`amount_sat` must be present when paying to a `SendDestination::LiquidAddress`".to_string() }); + }; - let fees_sat = match self.swapper.check_for_mrh(&req.invoice)? { - Some((lbtc_address, _)) => { - self.estimate_onchain_tx_fee(receiver_amount_sat, &lbtc_address, None) - .await? + ensure_sdk!( + liquid_address_data.network == self.config.network.into(), + PaymentError::InvalidNetwork { + err: format!( + "Cannot send payment from {} to {}", + Into::::into(self.config.network), + liquid_address_data.network + ) + } + ); + + receiver_amount_sat = amount_sat; + // TODO Ensure that `None` provides the lowest fees possible (0.01 sat/vbyte) + // once Esplora broadcast is enabled + fees_sat = self + .estimate_onchain_tx_fee( + receiver_amount_sat, + &liquid_address_data.address, + None, + ) + .await?; + + liquid_address_data.amount_sat = Some(receiver_amount_sat); + payment_destination = SendDestination::LiquidAddress { + address_data: liquid_address_data, + }; } - None => { - let lockup_fees_sat = self.estimate_lockup_tx_fee(receiver_amount_sat).await?; - lbtc_pair.fees.total(receiver_amount_sat) + lockup_fees_sat + InputType::Bolt11 { invoice } => { + self.ensure_send_is_not_self_transfer(&invoice.bolt11)?; + self.validate_invoice(&invoice.bolt11)?; + + receiver_amount_sat = invoice.amount_msat.ok_or(PaymentError::AmountMissing { + err: "Expected invoice with an amount".to_string(), + })? / 1000; + + if let Some(amount_sat) = req.amount_sat { + ensure_sdk!( + receiver_amount_sat == amount_sat, + PaymentError::Generic { err: "Amount in the payment request is not the same as the one in the invoice".to_string() } + ); + } + + let lbtc_pair = self.validate_submarine_pairs(receiver_amount_sat)?; + + fees_sat = match self.swapper.check_for_mrh(&invoice.bolt11)? { + Some((lbtc_address, _)) => { + self.estimate_onchain_tx_fee(receiver_amount_sat, &lbtc_address, None) + .await? + } + None => { + let lockup_fees_sat = + self.estimate_lockup_tx_fee(receiver_amount_sat).await?; + lbtc_pair.fees.total(receiver_amount_sat) + lockup_fees_sat + } + }; + payment_destination = SendDestination::Bolt11 { invoice }; + } + _ => { + return Err(PaymentError::Generic { + err: "Destination is not valid".to_string(), + }); } }; @@ -703,7 +776,7 @@ impl LiquidSdk { ); Ok(PrepareSendResponse { - invoice: req.invoice.clone(), + destination: payment_destination, fees_sat, }) } @@ -715,7 +788,7 @@ impl LiquidSdk { } } - /// Pays a Lightning invoice via a submarine swap. + /// Either pays a Lightning invoice via a submarine swap or sends funds directly to an address. /// /// Depending on [Config]'s `payment_timeout_sec`, this function will return: /// * [PaymentState::Pending] payment - if the payment could be initiated but didn't yet @@ -724,59 +797,128 @@ impl LiquidSdk { /// /// # Arguments /// - /// * `req` - The [PrepareSendResponse] from calling [LiquidSdk::prepare_send_payment] + /// * `req` - A [SendPaymentRequest], containing: + /// * `prepare_response` - the [PrepareSendResponse] returned by [LiquidSdk::prepare_send_payment] /// /// # Errors /// /// * [PaymentError::PaymentTimeout] - if the payment could not be initiated in this time pub async fn send_payment( &self, - req: &PrepareSendResponse, + req: &SendPaymentRequest, ) -> Result { self.ensure_is_started().await?; - self.ensure_send_is_not_self_transfer(&req.invoice)?; - self.validate_invoice(&req.invoice)?; + let PrepareSendResponse { + fees_sat, + destination: payment_destination, + } = &req.prepare_response; - let amount_sat = get_invoice_amount!(&req.invoice); - let payer_amount_sat = amount_sat + req.fees_sat; + match payment_destination { + SendDestination::LiquidAddress { + address_data: liquid_address_data, + } => { + let Some(amount_sat) = liquid_address_data.amount_sat else { + return Err(PaymentError::AmountMissing { err: "`amount_sat` must be present when paying to a `SendDestination::LiquidAddress`".to_string() }); + }; + + ensure_sdk!( + liquid_address_data.network == self.config.network.into(), + PaymentError::InvalidNetwork { + err: format!( + "Cannot send payment from {} to {}", + Into::::into(self.config.network), + liquid_address_data.network + ) + } + ); + + let payer_amount_sat = amount_sat + fees_sat; + ensure_sdk!( + payer_amount_sat <= self.get_info().await?.balance_sat, + PaymentError::InsufficientFunds + ); + + self.pay_liquid(liquid_address_data.clone(), amount_sat, *fees_sat) + .await + } + SendDestination::Bolt11 { invoice } => { + self.pay_invoice(&invoice.bolt11, *fees_sat).await + } + } + } + + async fn pay_invoice( + &self, + invoice: &str, + fees_sat: u64, + ) -> Result { + self.ensure_send_is_not_self_transfer(invoice)?; + self.validate_invoice(invoice)?; + + let amount_sat = get_invoice_amount!(invoice); + let payer_amount_sat = amount_sat + fees_sat; ensure_sdk!( payer_amount_sat <= self.get_info().await?.balance_sat, PaymentError::InsufficientFunds ); - match self.swapper.check_for_mrh(&req.invoice)? { + match self.swapper.check_for_mrh(invoice)? { // If we find a valid MRH, extract the BIP21 amount and address, then pay via onchain tx - Some((address, amount_btc)) => { - self.send_payment_via_mrh(req, &address, amount_btc).await + Some((address, _amount_sat)) => { + info!("Found MRH for L-BTC address {address} and amount_sat {amount_sat}"); + self.pay_liquid( + LiquidAddressData { + address, + network: self.config.network.into(), + asset_id: None, + amount_sat: None, + label: None, + message: None, + }, + amount_sat, + fees_sat, + ) + .await } // If no MRH found, perform usual swap - None => self.send_payment_via_swap(req).await, + None => self.send_payment_via_swap(invoice, fees_sat).await, } } - /// Performs a Send Payment by doing an onchain tx to the L-BTC address in the MRH. - async fn send_payment_via_mrh( + /// Performs a Send Payment by doing an onchain tx to a L-BTC address + async fn pay_liquid( &self, - req: &PrepareSendResponse, - lbtc_address: &str, - amount_btc: f64, + address_data: LiquidAddressData, + receiver_amount_sat: u64, + fees_sat: u64, ) -> Result { - let amount_sat: u64 = (amount_btc * 100_000_000.0) as u64; - info!("Found MRH for L-BTC address {lbtc_address} and amount_sat {amount_sat}"); - - let receiver_amount_sat = get_invoice_amount!(req.invoice); + // TODO Ensure that `None` provides the lowest fees possible (0.01 sat/vbyte) + // once Esplora broadcast is enabled + // Ensure we use the same fee-rate from the `PrepareSendResponse` + let fee_rate_sats_per_kvb = utils::derive_fee_rate_sats_per_kvb( + self.onchain_wallet.clone(), + receiver_amount_sat, + &address_data.address, + fees_sat, + ) + .await?; let tx = self .onchain_wallet - .build_tx(None, lbtc_address, receiver_amount_sat) + .build_tx( + Some(fee_rate_sats_per_kvb), + &address_data.address, + receiver_amount_sat, + ) .await?; - let onchain_fees_sat: u64 = tx.all_fees().values().sum(); - let payer_amount_sat = receiver_amount_sat + onchain_fees_sat; - info!("Built onchain L-BTC tx with receiver_amount_sat = {receiver_amount_sat}, fees_sat = {onchain_fees_sat}"); - info!("Built onchain L-BTC tx with ID {}", tx.txid()); let tx_id = tx.txid().to_string(); + let payer_amount_sat = receiver_amount_sat + fees_sat; + info!( + "Built onchain L-BTC tx with receiver_amount_sat = {receiver_amount_sat}, fees_sat = {fees_sat} and txid = {tx_id}" + ); + let tx_hex = lwk_wollet::elements::encode::serialize(&tx).to_lower_hex_string(); self.swapper .broadcast_tx(self.config.network.into(), &tx_hex)?; @@ -787,32 +929,40 @@ impl LiquidSdk { tx_id: tx_id.clone(), timestamp: Some(utils::now()), amount_sat: payer_amount_sat, - fees_sat: onchain_fees_sat, + fees_sat, payment_type: PaymentType::Send, is_confirmed: false, }; - self.persister.insert_or_update_payment(tx_data.clone())?; + let payment_details = Some(PaymentDetails::Liquid { + destination: address_data.to_uri().unwrap_or(address_data.address), + description: address_data + .message + .unwrap_or("Liquid transfer".to_string()), + }); + self.persister + .insert_or_update_payment(tx_data.clone(), payment_details.clone())?; self.emit_payment_updated(Some(tx_id)).await?; // Emit Pending event Ok(SendPaymentResponse { - payment: Payment::from_tx_data(tx_data, None), + payment: Payment::from_tx_data(tx_data, None, payment_details), }) } /// Performs a Send Payment by doing a swap (create it, fund it, track it, etc). async fn send_payment_via_swap( &self, - req: &PrepareSendResponse, + invoice: &str, + fees_sat: u64, ) -> Result { - let receiver_amount_sat = get_invoice_amount!(req.invoice); + let receiver_amount_sat = get_invoice_amount!(invoice); let lbtc_pair = self.validate_submarine_pairs(receiver_amount_sat)?; let lockup_tx_fees_sat = self.estimate_lockup_tx_fee(receiver_amount_sat).await?; ensure_sdk!( - req.fees_sat == lbtc_pair.fees.total(receiver_amount_sat) + lockup_tx_fees_sat, + fees_sat == lbtc_pair.fees.total(receiver_amount_sat) + lockup_tx_fees_sat, PaymentError::InvalidOrExpiredFees ); - let swap = match self.persister.fetch_send_swap_by_invoice(&req.invoice)? { + let swap = match self.persister.fetch_send_swap_by_invoice(invoice)? { Some(swap) => match swap.state { Pending => return Err(PaymentError::PaymentInProgress), Complete => return Err(PaymentError::AlreadyPaid), @@ -833,7 +983,7 @@ impl LiquidSdk { let create_response = self.swapper.create_send_swap(CreateSubmarineRequest { from: "L-BTC".to_string(), to: "BTC".to_string(), - invoice: req.invoice.to_string(), + invoice: invoice.to_string(), refund_public_key, pair_hash: Some(lbtc_pair.hash), referral_id: None, @@ -842,12 +992,12 @@ impl LiquidSdk { let swap_id = &create_response.id; let create_response_json = SendSwap::from_boltz_struct_to_json(&create_response, swap_id)?; - let description = get_invoice_description!(req.invoice); + let description = get_invoice_description!(invoice); - let payer_amount_sat = req.fees_sat + receiver_amount_sat; + let payer_amount_sat = fees_sat + receiver_amount_sat; let swap = SendSwap { id: swap_id.clone(), - invoice: req.invoice.clone(), + invoice: invoice.to_string(), description, preimage: None, payer_amount_sat, @@ -983,7 +1133,7 @@ impl LiquidSdk { /// /// * `req` - the [PayOnchainRequest] containing: /// * `address` - the Bitcoin address to pay to - /// * `prepare_res` - the [PreparePayOnchainResponse] from calling [LiquidSdk::prepare_pay_onchain] + /// * `prepare_response` - the [PreparePayOnchainResponse] from calling [LiquidSdk::prepare_pay_onchain] /// /// # Errors /// @@ -994,9 +1144,9 @@ impl LiquidSdk { ) -> Result { self.ensure_is_started().await?; - let receiver_amount_sat = req.prepare_res.receiver_amount_sat; + let receiver_amount_sat = req.prepare_response.receiver_amount_sat; let pair = self.validate_chain_pairs(Direction::Outgoing, receiver_amount_sat)?; - let claim_fees_sat = req.prepare_res.claim_fees_sat; + let claim_fees_sat = req.prepare_response.claim_fees_sat; let server_fees_sat = pair.fees.server(); let server_lockup_amount_sat = receiver_amount_sat + claim_fees_sat; let lockup_fees_sat = self @@ -1004,7 +1154,7 @@ impl LiquidSdk { .await?; ensure_sdk!( - req.prepare_res.total_fees_sat + req.prepare_response.total_fees_sat == pair.fees.boltz(server_lockup_amount_sat) + lockup_fees_sat + claim_fees_sat @@ -1012,7 +1162,7 @@ impl LiquidSdk { PaymentError::InvalidOrExpiredFees ); - let payer_amount_sat = req.prepare_res.total_fees_sat + receiver_amount_sat; + let payer_amount_sat = req.prepare_response.total_fees_sat + receiver_amount_sat; ensure_sdk!( payer_amount_sat <= self.get_info().await?.balance_sat, PaymentError::InsufficientFunds @@ -1047,7 +1197,7 @@ impl LiquidSdk { let create_response_json = ChainSwap::from_boltz_struct_to_json(&create_response, swap_id)?; let accept_zero_conf = server_lockup_amount_sat <= pair.limits.maximal_zero_conf; - let payer_amount_sat = req.prepare_res.total_fees_sat + receiver_amount_sat; + let payer_amount_sat = req.prepare_response.total_fees_sat + receiver_amount_sat; let claim_address = req.address.clone(); let swap = ChainSwap { @@ -1088,7 +1238,7 @@ impl LiquidSdk { let timeout_fut = tokio::time::sleep(Duration::from_secs(self.config.payment_timeout_sec)); tokio::pin!(timeout_fut); - let swap_id = swap.id(); + let expected_swap_id = swap.id(); let mut events_stream = self.event_manager.subscribe(); let mut maybe_payment: Option = None; @@ -1099,34 +1249,35 @@ impl LiquidSdk { None => { debug!("Timeout occurred without payment, set swap to timed out"); match swap { - Swap::Send(_) => self.send_swap_state_handler.update_swap_info(&swap_id, TimedOut, None, None, None).await?, - Swap::Chain(_) => self.chain_swap_state_handler.update_swap_info(&swap_id, TimedOut, None, None, None, None).await?, + Swap::Send(_) => self.send_swap_state_handler.update_swap_info(&expected_swap_id, TimedOut, None, None, None).await?, + Swap::Chain(_) => self.chain_swap_state_handler.update_swap_info(&expected_swap_id, TimedOut, None, None, None, None).await?, _ => () } return Err(PaymentError::PaymentTimeout) }, }, event = events_stream.recv() => match event { - Ok(SdkEvent::PaymentPending { details }) => match details.swap_id.clone() { - Some(id) if id == swap_id => match accept_zero_conf { - true => { - debug!("Received Send Payment pending event with zero-conf accepted"); - return Ok(details) + Ok(SdkEvent::PaymentPending { details: payment }) => { + let maybe_payment_swap_id = payment.details.as_ref().and_then(|d|d.get_swap_id()); + if matches!(maybe_payment_swap_id, Some(swap_id) if swap_id == expected_swap_id) { + match accept_zero_conf { + true => { + debug!("Received Send Payment pending event with zero-conf accepted"); + return Ok(payment) + } + false => { + debug!("Received Send Payment pending event, waiting for confirmation"); + maybe_payment = Some(payment); + } } - false => { - debug!("Received Send Payment pending event, waiting for confirmation"); - maybe_payment = Some(details); - } - }, - _ => error!("Received Send Payment pending event for payment without swap ID"), + }; }, - Ok(SdkEvent::PaymentSucceeded { details }) => match details.swap_id.clone() - { - Some(id) if id == swap_id => { + Ok(SdkEvent::PaymentSucceeded { details: payment }) => { + let maybe_payment_swap_id = payment.details.as_ref().and_then(|d| d.get_swap_id()); + if matches!(maybe_payment_swap_id, Some(swap_id) if swap_id == expected_swap_id) { debug!("Received Send Payment succeed event"); - return Ok(details); + return Ok(payment); } - _ => error!("Received Send Payment succeed event for payment without swap ID"), }, Ok(event) => debug!("Unhandled event: {event:?}"), Err(e) => debug!("Received error waiting for event: {e:?}"), @@ -1139,57 +1290,138 @@ impl LiquidSdk { /// /// # Arguments /// - /// * `req` - the [PrepareReceivePaymentRequest] containing: + /// * `req` - the [PrepareReceiveRequest] containing: /// * `payer_amount_sat` - the amount in satoshis to be paid by the payer + /// * `payment_method` - the supported payment methods; either an invoice, a Liquid address or a Bitcoin address pub async fn prepare_receive_payment( &self, - req: &PrepareReceivePaymentRequest, - ) -> Result { + req: &PrepareReceiveRequest, + ) -> Result { self.ensure_is_started().await?; - let reverse_pair = self - .swapper - .get_reverse_swap_pairs()? - .ok_or(PaymentError::PairsNotFound)?; - let payer_amount_sat = req.payer_amount_sat; - let fees_sat = reverse_pair.fees.total(req.payer_amount_sat); + let fees_sat; + match req.payment_method { + PaymentMethod::Lightning => { + let Some(amount_sat) = req.payer_amount_sat else { + return Err(PaymentError::AmountMissing { err: "`amount_sat` must be specified when `PaymentMethod::Lightning` is used.".to_string() }); + }; + let reverse_pair = self + .swapper + .get_reverse_swap_pairs()? + .ok_or(PaymentError::PairsNotFound)?; - ensure_sdk!(payer_amount_sat > fees_sat, PaymentError::AmountOutOfRange); + fees_sat = reverse_pair.fees.total(amount_sat); - reverse_pair - .limits - .within(payer_amount_sat) - .map_err(|_| PaymentError::AmountOutOfRange)?; + ensure_sdk!(amount_sat > fees_sat, PaymentError::AmountOutOfRange); - debug!("Preparing Receive Swap with: payer_amount_sat {payer_amount_sat} sat, fees_sat {fees_sat} sat"); + reverse_pair + .limits + .within(amount_sat) + .map_err(|_| PaymentError::AmountOutOfRange)?; - Ok(PrepareReceivePaymentResponse { - payer_amount_sat, + debug!( + "Preparing Lightning Receive Swap with: amount_sat {amount_sat} sat, fees_sat {fees_sat} sat" + ); + } + PaymentMethod::BitcoinAddress => { + let Some(amount_sat) = req.payer_amount_sat else { + return Err(PaymentError::AmountMissing { err: "`amount_sat` must be specified when `PaymentMethod::BitcoinAddress` is used.".to_string() }); + }; + let pair = self.validate_chain_pairs(Direction::Incoming, amount_sat)?; + let claim_fees_sat = pair.fees.claim_estimate(); + let server_fees_sat = pair.fees.server(); + fees_sat = pair.fees.boltz(amount_sat) + claim_fees_sat + server_fees_sat; + debug!( + "Preparing Chain Receive Swap with: amount_sat {amount_sat} sat, fees_sat {fees_sat} sat" + ); + } + PaymentMethod::LiquidAddress => { + fees_sat = 0; + debug!( + "Preparing Liquid Receive Swap with: amount_sat {:?} sat, fees_sat {fees_sat} sat", + req.payer_amount_sat + ); + } + }; + + Ok(PrepareReceiveResponse { + payer_amount_sat: req.payer_amount_sat, fees_sat, + payment_method: req.payment_method.clone(), }) } - /// Receive a Lightning payment via a reverse submarine swap. + /// Receive a Lightning payment via a reverse submarine swap, a chain swap or via direct Liquid + /// payment. /// /// # Arguments /// /// * `req` - the [ReceivePaymentRequest] containing: /// * `description` - the optional payment description - /// * `prepare_res` - the [PrepareReceivePaymentResponse] from calling [LiquidSdk::prepare_receive_payment] + /// * `prepare_response` - the [PrepareReceiveResponse] from calling [LiquidSdk::prepare_receive_payment] /// /// # Returns /// /// * A [ReceivePaymentResponse] containing: - /// * `invoice` - the bolt11 Lightning invoice that should be paid + /// * `destination` - the final destination to be paid by the payer, either a BIP21 URI (Liquid or Bitcoin), a Liquid address or an invoice pub async fn receive_payment( &self, req: &ReceivePaymentRequest, ) -> Result { self.ensure_is_started().await?; - let payer_amount_sat = req.prepare_res.payer_amount_sat; - let fees_sat = req.prepare_res.fees_sat; + let PrepareReceiveResponse { + payment_method, + payer_amount_sat: amount_sat, + fees_sat, + } = &req.prepare_response; + match payment_method { + PaymentMethod::Lightning => { + let Some(amount_sat) = amount_sat else { + return Err(PaymentError::AmountMissing { err: "`amount_sat` must be specified when `PaymentMethod::Lightning` is used.".to_string() }); + }; + self.create_receive_swap(*amount_sat, *fees_sat, req.description.clone()) + .await + } + PaymentMethod::BitcoinAddress => { + let Some(amount_sat) = amount_sat else { + return Err(PaymentError::AmountMissing { err: "`amount_sat` must be specified when `PaymentMethod::BitcoinAddress` is used.".to_string() }); + }; + self.receive_onchain(*amount_sat, *fees_sat).await + } + PaymentMethod::LiquidAddress => { + let address = self.onchain_wallet.next_unused_address().await?.to_string(); + + let receive_destination = match amount_sat { + Some(amount_sat) => LiquidAddressData { + address: address.to_string(), + network: self.config.network.into(), + amount_sat: Some(*amount_sat), + asset_id: Some(AssetId::LIQUID_BTC.to_hex()), + label: None, + message: req.description.clone(), + } + .to_uri() + .map_err(|e| PaymentError::Generic { + err: format!("Could not build BIP21 URI: {e:?}"), + })?, + None => address, + }; + + Ok(ReceivePaymentResponse { + destination: receive_destination, + }) + } + } + } + + async fn create_receive_swap( + &self, + payer_amount_sat: u64, + fees_sat: u64, + description: Option, + ) -> Result { let reverse_pair = self .swapper .get_reverse_swap_pairs()? @@ -1219,7 +1451,7 @@ impl LiquidSdk { to: "L-BTC".to_string(), preimage_hash: preimage.sha256, claim_public_key: keypair.public_key().into(), - description: req.description.clone(), + description, address: Some(mrh_addr_str.clone()), address_signature: Some(mrh_addr_hash_sig.to_hex()), referral_id: None, @@ -1286,31 +1518,7 @@ impl LiquidSdk { self.status_stream.track_swap_id(&swap_id)?; Ok(ReceivePaymentResponse { - id: swap_id, - invoice: invoice.to_string(), - }) - } - - /// Prepares to receive from a Bitcoin transaction via a chain swap. - /// - /// # Arguments - /// - /// * `req` - the [PrepareReceiveOnchainRequest] containing: - /// * `payer_amount_sat` - the amount in satoshi that will be paid by the payer - pub async fn prepare_receive_onchain( - &self, - req: &PrepareReceiveOnchainRequest, - ) -> Result { - self.ensure_is_started().await?; - - let payer_amount_sat = req.payer_amount_sat; - let pair = self.validate_chain_pairs(Direction::Incoming, payer_amount_sat)?; - let claim_fees_sat = pair.fees.claim_estimate(); - let server_fees_sat = pair.fees.server(); - - Ok(PrepareReceiveOnchainResponse { - payer_amount_sat, - fees_sat: pair.fees.boltz(payer_amount_sat) + claim_fees_sat + server_fees_sat, + destination: invoice.to_string(), }) } @@ -1389,25 +1597,14 @@ impl LiquidSdk { } /// Receive from a Bitcoin transaction via a chain swap. - /// - /// # Arguments - /// - /// * `req` - The [PrepareReceiveOnchainResponse] from calling [LiquidSdk::prepare_receive_onchain] - /// - /// # Returns - /// - /// * A [ReceiveOnchainResponse] containing: - /// * `address` - the Bitcoin address the payer should pay to - /// * `bip21` - the BIP-21 URI scheme to pay to. See - pub async fn receive_onchain( + async fn receive_onchain( &self, - req: &PrepareReceiveOnchainResponse, - ) -> Result { + payer_amount_sat: u64, + fees_sat: u64, + ) -> Result { self.ensure_is_started().await?; - let swap = self - .create_chain_swap(req.payer_amount_sat, req.fees_sat) - .await?; + let swap = self.create_chain_swap(payer_amount_sat, fees_sat).await?; let create_response = swap.get_boltz_create_response()?; let address = create_response.lockup_details.lockup_address; @@ -1416,7 +1613,7 @@ impl LiquidSdk { "bitcoin:{address}?amount={amount}&label=Send%20to%20L-BTC%20address" )); - Ok(ReceiveOnchainResponse { address, bip21 }) + Ok(ReceivePaymentResponse { destination: bip21 }) } /// List all failed chain swaps that need to be refunded. @@ -1491,19 +1688,30 @@ impl LiquidSdk { req: &PrepareBuyBitcoinRequest, ) -> Result { if self.config.network != LiquidNetwork::Mainnet { - return Err(PaymentError::Generic { + return Err(PaymentError::InvalidNetwork { err: "Can only buy bitcoin on Mainnet".to_string(), }); } let res = self - .prepare_receive_onchain(&PrepareReceiveOnchainRequest { - payer_amount_sat: req.amount_sat, + .prepare_receive_payment(&PrepareReceiveRequest { + payment_method: PaymentMethod::BitcoinAddress, + payer_amount_sat: Some(req.amount_sat), }) .await?; + + let Some(amount_sat) = res.payer_amount_sat else { + return Err(PaymentError::Generic { + err: format!( + "Expected field `amount_sat` from response, got {:?}", + res.payer_amount_sat + ), + }); + }; + Ok(PrepareBuyBitcoinResponse { provider: req.provider, - amount_sat: res.payer_amount_sat, + amount_sat, fees_sat: res.fees_sat, }) } @@ -1513,16 +1721,23 @@ impl LiquidSdk { /// # Arguments /// /// * `req` - the [BuyBitcoinRequest] containing: - /// * `prepare_res` - the [PrepareBuyBitcoinResponse] from calling [LiquidSdk::prepare_buy_bitcoin] + /// * `prepare_response` - the [PrepareBuyBitcoinResponse] from calling [LiquidSdk::prepare_buy_bitcoin] /// * `redirect_url` - the optional redirect URL the provider should redirect to after purchase pub async fn buy_bitcoin(&self, req: &BuyBitcoinRequest) -> Result { let swap = self - .create_chain_swap(req.prepare_res.amount_sat, req.prepare_res.fees_sat) + .create_chain_swap( + req.prepare_response.amount_sat, + req.prepare_response.fees_sat, + ) .await?; Ok(self .buy_bitcoin_service - .buy_bitcoin(req.prepare_res.provider, &swap, req.redirect_url.clone()) + .buy_bitcoin( + req.prepare_response.provider, + &swap, + req.redirect_url.clone(), + ) .await?) } @@ -1556,17 +1771,20 @@ impl LiquidSdk { let is_tx_confirmed = tx.height.is_some(); let amount_sat = tx.balance.values().sum::(); - self.persister.insert_or_update_payment(PaymentTxData { - tx_id: tx_id.clone(), - timestamp: tx.timestamp, - amount_sat: amount_sat.unsigned_abs(), - fees_sat: tx.fee, - payment_type: match amount_sat >= 0 { - true => PaymentType::Receive, - false => PaymentType::Send, + self.persister.insert_or_update_payment( + PaymentTxData { + tx_id: tx_id.clone(), + timestamp: tx.timestamp, + amount_sat: amount_sat.unsigned_abs(), + fees_sat: tx.fee, + payment_type: match amount_sat >= 0 { + true => PaymentType::Receive, + false => PaymentType::Send, + }, + is_confirmed: is_tx_confirmed, }, - is_confirmed: is_tx_confirmed, - })?; + None, + )?; if let Some(swap) = pending_receive_swaps_by_claim_tx_id.get(&tx_id) { if is_tx_confirmed { @@ -1722,21 +1940,32 @@ impl LiquidSdk { Ok(LnUrlPayResult::EndpointError { data: e }) } ValidatedCallbackResponse::EndpointSuccess { data: cb } => { - let pay_req = self + let prepare_response = self .prepare_send_payment(&PrepareSendRequest { - invoice: cb.pr.clone(), + destination: cb.pr.clone(), + amount_sat: None, }) .await?; - let payment = self.send_payment(&pay_req).await?.payment; + let payment = self + .send_payment(&SendPaymentRequest { prepare_response }) + .await? + .payment; let maybe_sa_processed: Option = match cb.success_action { Some(sa) => { let processed_sa = match sa { // For AES, we decrypt the contents on the fly SuccessAction::Aes(data) => { - let preimage_str = payment - .preimage + let Some(PaymentDetails::Lightning { preimage, .. }) = + &payment.details + else { + return Err(LnUrlPayError::Generic { + err: format!("Invalid payment type: expected type `PaymentDetails::Lightning`, got payment details {:?}.", payment.details), + }); + }; + + let preimage_str = preimage .clone() .ok_or(SdkError::Generic { err: "Payment successful but no preimage found".to_string(), @@ -1787,23 +2016,29 @@ impl LiquidSdk { &self, req: LnUrlWithdrawRequest, ) -> Result { - let prepare_res = self + let prepare_response = self .prepare_receive_payment(&{ - PrepareReceivePaymentRequest { - payer_amount_sat: req.amount_msat / 1_000, + PrepareReceiveRequest { + payment_method: PaymentMethod::Lightning, + payer_amount_sat: Some(req.amount_msat / 1_000), } }) .await?; let receive_res = self .receive_payment(&ReceivePaymentRequest { - prepare_res, + prepare_response, description: None, }) .await?; - let invoice = parse_invoice(&receive_res.invoice)?; - let res = validate_lnurl_withdraw(req.data, invoice).await?; - Ok(res) + if let Ok(invoice) = parse_invoice(&receive_res.destination) { + let res = validate_lnurl_withdraw(req.data, invoice).await?; + Ok(res) + } else { + Err(LnUrlWithdrawError::Generic { + err: "Received unexpected output from receive request".to_string(), + }) + } } /// Third and last step of LNURL-auth. The first step is [parse], which also validates the LNURL destination @@ -2288,7 +2523,7 @@ mod tests { Some(true) // sets `update.zero_conf_rejected` ); assert_eq!(persisted_swap.user_lockup_tx_id, Some(mock_tx_id.clone())); - assert_eq!(persisted_swap.accept_zero_conf, false); + assert!(!persisted_swap.accept_zero_conf); } // Verify that `TransactionServerMempool` correctly: diff --git a/lib/core/src/send_swap.rs b/lib/core/src/send_swap.rs index 8f3f27c..2ee9663 100644 --- a/lib/core/src/send_swap.rs +++ b/lib/core/src/send_swap.rs @@ -86,14 +86,17 @@ impl SendSwapStateHandler { // We insert a pseudo-lockup-tx in case LWK fails to pick up the new mempool tx for a while // This makes the tx known to the SDK (get_info, list_payments) instantly - self.persister.insert_or_update_payment(PaymentTxData { - tx_id: lockup_tx_id.clone(), - timestamp: Some(utils::now()), - amount_sat: swap.payer_amount_sat, - fees_sat: lockup_tx_fees_sat, - payment_type: PaymentType::Send, - is_confirmed: false, - })?; + self.persister.insert_or_update_payment( + PaymentTxData { + tx_id: lockup_tx_id.clone(), + timestamp: Some(utils::now()), + amount_sat: swap.payer_amount_sat, + fees_sat: lockup_tx_fees_sat, + payment_type: PaymentType::Send, + is_confirmed: false, + }, + None, + )?; self.update_swap_info(id, Pending, None, Some(&lockup_tx_id), None) .await?; @@ -229,7 +232,9 @@ impl SendSwapStateHandler { let lockup_tx = self .onchain_wallet .build_tx( - self.config.lowball_fee_rate_msat_per_vbyte(), + self.config + .lowball_fee_rate_msat_per_vbyte() + .map(|v| v as f32), &create_response.address, create_response.expected_amount, ) diff --git a/lib/core/src/test_utils/swapper.rs b/lib/core/src/test_utils/swapper.rs index 3a6ed8a..499054c 100644 --- a/lib/core/src/test_utils/swapper.rs +++ b/lib/core/src/test_utils/swapper.rs @@ -109,7 +109,7 @@ impl Swapper for MockSwapper { hash: generate_random_string(10), rate: 0.0, limits: PairLimits { - maximal: std::u64::MAX, + maximal: u64::MAX, minimal: 0, maximal_zero_conf: 100_000, }, @@ -154,7 +154,7 @@ impl Swapper for MockSwapper { hash: generate_random_string(10), rate: 0.0, limits: PairLimits { - maximal: std::u64::MAX, + maximal: u64::MAX, minimal: 0, maximal_zero_conf: 100_000, }, @@ -260,7 +260,7 @@ impl Swapper for MockSwapper { hash: "".to_string(), rate: 0.0, limits: ReverseLimits { - maximal: std::u64::MAX, + maximal: u64::MAX, minimal: 0, }, fees: ReverseFees { diff --git a/lib/core/src/utils.rs b/lib/core/src/utils.rs index 7d4ab92..cbda9e2 100644 --- a/lib/core/src/utils.rs +++ b/lib/core/src/utils.rs @@ -1,4 +1,5 @@ use std::str::FromStr; +use std::sync::Arc; use std::time::{SystemTime, UNIX_EPOCH}; use crate::error::{PaymentError, SdkResult}; @@ -6,12 +7,14 @@ use crate::prelude::{ Config, LiquidNetwork, SendSwap, LOWBALL_FEE_RATE_SAT_PER_VBYTE, STANDARD_FEE_RATE_SAT_PER_VBYTE, }; +use crate::wallet::OnchainWallet; use anyhow::{anyhow, Result}; use boltz_client::boltz::{ BoltzApiClientV2, Cooperative, BOLTZ_MAINNET_URL_V2, BOLTZ_TESTNET_URL_V2, }; use boltz_client::network::electrum::ElectrumConfig; use boltz_client::Amount; +use log::debug; use lwk_wollet::elements::encode::deserialize; use lwk_wollet::elements::hex::FromHex; use lwk_wollet::elements::{ @@ -59,6 +62,30 @@ pub(crate) fn deserialize_tx_hex(tx_hex: &str) -> Result { )?)?) } +pub(crate) async fn derive_fee_rate_sats_per_kvb( + wallet: Arc, + amount_sat: u64, + recipient_address: &str, + absolute_fees_sat: u64, +) -> Result { + let standard_fees_sat = wallet + .build_tx(None, recipient_address, amount_sat) + .await? + .all_fees() + .values() + .sum::() as f64; + + // Multiply sats/vb value by 1000 i.e. 1.0 sat/byte = 1000.0 sat/kvb + // We calculate using f64 and convert to f32 in the last step, so we keep the maximum precision possible + let result_sat_per_vb = + STANDARD_FEE_RATE_SAT_PER_VBYTE * absolute_fees_sat as f64 / standard_fees_sat; + let result_sat_per_kvb = result_sat_per_vb * 1000.0; + let result_sat_per_kvb_f32 = result_sat_per_kvb as f32; + debug!("derive_fee_rate_sats_per_kvb: result_sat_per_kvb_f32 {} from inputs: absolute_fees_sat {}, result_sat_per_kvb: {}", + result_sat_per_kvb_f32, absolute_fees_sat, result_sat_per_kvb); + Ok(result_sat_per_kvb_f32) +} + pub(crate) fn estimate_refund_fees( swap: &SendSwap, config: &Config, @@ -110,5 +137,5 @@ pub(crate) fn estimate_refund_fees( }; let dummy_tx = swap_tx.sign_refund(&swap.get_refund_keypair()?, dummy_fees, cooperative)?; - Ok((dummy_tx.vsize() as f32 * fee_rate).ceil() as u64) + Ok((dummy_tx.vsize() as f64 * fee_rate).ceil() as u64) } diff --git a/lib/core/src/wallet.rs b/lib/core/src/wallet.rs index 89f64a5..b91a6b3 100644 --- a/lib/core/src/wallet.rs +++ b/lib/core/src/wallet.rs @@ -28,7 +28,7 @@ pub trait OnchainWallet: Send + Sync { /// Build a transaction to send funds to a recipient async fn build_tx( &self, - fee_rate: Option, + fee_rate_sats_per_kvb: Option, recipient_address: &str, amount_sat: u64, ) -> Result; @@ -103,7 +103,7 @@ impl OnchainWallet for LiquidOnchainWallet { /// Build a transaction to send funds to a recipient async fn build_tx( &self, - fee_rate: Option, + fee_rate_sats_per_kvb: Option, recipient_address: &str, amount_sat: u64, ) -> Result { @@ -119,7 +119,7 @@ impl OnchainWallet for LiquidOnchainWallet { })?, amount_sat, )? - .fee_rate(fee_rate) + .fee_rate(fee_rate_sats_per_kvb) .finish(&lwk_wollet)?; let signer = AnySigner::Software(self.lwk_signer.clone()); signer.sign(&mut pset)?; diff --git a/packages/dart/lib/src/bindings.dart b/packages/dart/lib/src/bindings.dart index bf52713..b5d6464 100644 --- a/packages/dart/lib/src/bindings.dart +++ b/packages/dart/lib/src/bindings.dart @@ -67,16 +67,12 @@ abstract class BindingLiquidSdk implements RustOpaqueInterface { Future preparePayOnchain({required PreparePayOnchainRequest req}); - Future prepareReceiveOnchain({required PrepareReceiveOnchainRequest req}); - - Future prepareReceivePayment({required PrepareReceivePaymentRequest req}); + Future prepareReceivePayment({required PrepareReceiveRequest req}); Future prepareRefund({required PrepareRefundRequest req}); Future prepareSendPayment({required PrepareSendRequest req}); - Future receiveOnchain({required PrepareReceiveOnchainResponse req}); - Future receivePayment({required ReceivePaymentRequest req}); Future recommendedFees(); @@ -87,7 +83,7 @@ abstract class BindingLiquidSdk implements RustOpaqueInterface { void restore({required RestoreRequest req}); - Future sendPayment({required PrepareSendResponse req}); + Future sendPayment({required SendPaymentRequest req}); Future sync(); } diff --git a/packages/dart/lib/src/error.dart b/packages/dart/lib/src/error.dart index 71a3a3c..0ac0cb2 100644 --- a/packages/dart/lib/src/error.dart +++ b/packages/dart/lib/src/error.dart @@ -16,6 +16,12 @@ sealed class PaymentError with _$PaymentError implements FrbException { const factory PaymentError.alreadyPaid() = PaymentError_AlreadyPaid; const factory PaymentError.paymentInProgress() = PaymentError_PaymentInProgress; const factory PaymentError.amountOutOfRange() = PaymentError_AmountOutOfRange; + const factory PaymentError.amountMissing({ + required String err, + }) = PaymentError_AmountMissing; + const factory PaymentError.invalidNetwork({ + required String err, + }) = PaymentError_InvalidNetwork; const factory PaymentError.generic({ required String err, }) = PaymentError_Generic; diff --git a/packages/dart/lib/src/error.freezed.dart b/packages/dart/lib/src/error.freezed.dart index 9b158f0..4df3bc2 100644 --- a/packages/dart/lib/src/error.freezed.dart +++ b/packages/dart/lib/src/error.freezed.dart @@ -212,6 +212,164 @@ abstract class PaymentError_AmountOutOfRange extends PaymentError { const PaymentError_AmountOutOfRange._() : super._(); } +/// @nodoc +abstract class _$$PaymentError_AmountMissingImplCopyWith<$Res> { + factory _$$PaymentError_AmountMissingImplCopyWith( + _$PaymentError_AmountMissingImpl value, $Res Function(_$PaymentError_AmountMissingImpl) then) = + __$$PaymentError_AmountMissingImplCopyWithImpl<$Res>; + @useResult + $Res call({String err}); +} + +/// @nodoc +class __$$PaymentError_AmountMissingImplCopyWithImpl<$Res> + extends _$PaymentErrorCopyWithImpl<$Res, _$PaymentError_AmountMissingImpl> + implements _$$PaymentError_AmountMissingImplCopyWith<$Res> { + __$$PaymentError_AmountMissingImplCopyWithImpl( + _$PaymentError_AmountMissingImpl _value, $Res Function(_$PaymentError_AmountMissingImpl) _then) + : super(_value, _then); + + /// Create a copy of PaymentError + /// with the given fields replaced by the non-null parameter values. + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? err = null, + }) { + return _then(_$PaymentError_AmountMissingImpl( + err: null == err + ? _value.err + : err // ignore: cast_nullable_to_non_nullable + as String, + )); + } +} + +/// @nodoc + +class _$PaymentError_AmountMissingImpl extends PaymentError_AmountMissing { + const _$PaymentError_AmountMissingImpl({required this.err}) : super._(); + + @override + final String err; + + @override + String toString() { + return 'PaymentError.amountMissing(err: $err)'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _$PaymentError_AmountMissingImpl && + (identical(other.err, err) || other.err == err)); + } + + @override + int get hashCode => Object.hash(runtimeType, err); + + /// Create a copy of PaymentError + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + @override + @pragma('vm:prefer-inline') + _$$PaymentError_AmountMissingImplCopyWith<_$PaymentError_AmountMissingImpl> get copyWith => + __$$PaymentError_AmountMissingImplCopyWithImpl<_$PaymentError_AmountMissingImpl>(this, _$identity); +} + +abstract class PaymentError_AmountMissing extends PaymentError { + const factory PaymentError_AmountMissing({required final String err}) = _$PaymentError_AmountMissingImpl; + const PaymentError_AmountMissing._() : super._(); + + String get err; + + /// Create a copy of PaymentError + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + _$$PaymentError_AmountMissingImplCopyWith<_$PaymentError_AmountMissingImpl> get copyWith => + throw _privateConstructorUsedError; +} + +/// @nodoc +abstract class _$$PaymentError_InvalidNetworkImplCopyWith<$Res> { + factory _$$PaymentError_InvalidNetworkImplCopyWith( + _$PaymentError_InvalidNetworkImpl value, $Res Function(_$PaymentError_InvalidNetworkImpl) then) = + __$$PaymentError_InvalidNetworkImplCopyWithImpl<$Res>; + @useResult + $Res call({String err}); +} + +/// @nodoc +class __$$PaymentError_InvalidNetworkImplCopyWithImpl<$Res> + extends _$PaymentErrorCopyWithImpl<$Res, _$PaymentError_InvalidNetworkImpl> + implements _$$PaymentError_InvalidNetworkImplCopyWith<$Res> { + __$$PaymentError_InvalidNetworkImplCopyWithImpl( + _$PaymentError_InvalidNetworkImpl _value, $Res Function(_$PaymentError_InvalidNetworkImpl) _then) + : super(_value, _then); + + /// Create a copy of PaymentError + /// with the given fields replaced by the non-null parameter values. + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? err = null, + }) { + return _then(_$PaymentError_InvalidNetworkImpl( + err: null == err + ? _value.err + : err // ignore: cast_nullable_to_non_nullable + as String, + )); + } +} + +/// @nodoc + +class _$PaymentError_InvalidNetworkImpl extends PaymentError_InvalidNetwork { + const _$PaymentError_InvalidNetworkImpl({required this.err}) : super._(); + + @override + final String err; + + @override + String toString() { + return 'PaymentError.invalidNetwork(err: $err)'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _$PaymentError_InvalidNetworkImpl && + (identical(other.err, err) || other.err == err)); + } + + @override + int get hashCode => Object.hash(runtimeType, err); + + /// Create a copy of PaymentError + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + @override + @pragma('vm:prefer-inline') + _$$PaymentError_InvalidNetworkImplCopyWith<_$PaymentError_InvalidNetworkImpl> get copyWith => + __$$PaymentError_InvalidNetworkImplCopyWithImpl<_$PaymentError_InvalidNetworkImpl>(this, _$identity); +} + +abstract class PaymentError_InvalidNetwork extends PaymentError { + const factory PaymentError_InvalidNetwork({required final String err}) = _$PaymentError_InvalidNetworkImpl; + const PaymentError_InvalidNetwork._() : super._(); + + String get err; + + /// Create a copy of PaymentError + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + _$$PaymentError_InvalidNetworkImplCopyWith<_$PaymentError_InvalidNetworkImpl> get copyWith => + throw _privateConstructorUsedError; +} + /// @nodoc abstract class _$$PaymentError_GenericImplCopyWith<$Res> { factory _$$PaymentError_GenericImplCopyWith( diff --git a/packages/dart/lib/src/frb_generated.dart b/packages/dart/lib/src/frb_generated.dart index 8627aa0..42e9700 100644 --- a/packages/dart/lib/src/frb_generated.dart +++ b/packages/dart/lib/src/frb_generated.dart @@ -55,7 +55,7 @@ class RustLib extends BaseEntrypoint { String get codegenVersion => '2.2.0'; @override - int get rustContentHash => -119028624; + int get rustContentHash => -1074530283; static const kDefaultExternalLibraryLoaderConfig = ExternalLibraryLoaderConfig( stem: 'breez_sdk_liquid', @@ -112,11 +112,8 @@ abstract class RustLibApi extends BaseApi { Future crateBindingsBindingLiquidSdkPreparePayOnchain( {required BindingLiquidSdk that, required PreparePayOnchainRequest req}); - Future crateBindingsBindingLiquidSdkPrepareReceiveOnchain( - {required BindingLiquidSdk that, required PrepareReceiveOnchainRequest req}); - - Future crateBindingsBindingLiquidSdkPrepareReceivePayment( - {required BindingLiquidSdk that, required PrepareReceivePaymentRequest req}); + Future crateBindingsBindingLiquidSdkPrepareReceivePayment( + {required BindingLiquidSdk that, required PrepareReceiveRequest req}); Future crateBindingsBindingLiquidSdkPrepareRefund( {required BindingLiquidSdk that, required PrepareRefundRequest req}); @@ -124,9 +121,6 @@ abstract class RustLibApi extends BaseApi { Future crateBindingsBindingLiquidSdkPrepareSendPayment( {required BindingLiquidSdk that, required PrepareSendRequest req}); - Future crateBindingsBindingLiquidSdkReceiveOnchain( - {required BindingLiquidSdk that, required PrepareReceiveOnchainResponse req}); - Future crateBindingsBindingLiquidSdkReceivePayment( {required BindingLiquidSdk that, required ReceivePaymentRequest req}); @@ -140,7 +134,7 @@ abstract class RustLibApi extends BaseApi { void crateBindingsBindingLiquidSdkRestore({required BindingLiquidSdk that, required RestoreRequest req}); Future crateBindingsBindingLiquidSdkSendPayment( - {required BindingLiquidSdk that, required PrepareSendResponse req}); + {required BindingLiquidSdk that, required SendPaymentRequest req}); Future crateBindingsBindingLiquidSdkSync({required BindingLiquidSdk that}); @@ -629,44 +623,18 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { ); @override - Future crateBindingsBindingLiquidSdkPrepareReceiveOnchain( - {required BindingLiquidSdk that, required PrepareReceiveOnchainRequest req}) { + Future crateBindingsBindingLiquidSdkPrepareReceivePayment( + {required BindingLiquidSdk that, required PrepareReceiveRequest req}) { return handler.executeNormal(NormalTask( callFfi: (port_) { var arg0 = cst_encode_Auto_Ref_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerBindingLiquidSdk( that); - var arg1 = cst_encode_box_autoadd_prepare_receive_onchain_request(req); - return wire.wire__crate__bindings__BindingLiquidSdk_prepare_receive_onchain(port_, arg0, arg1); - }, - codec: DcoCodec( - decodeSuccessData: dco_decode_prepare_receive_onchain_response, - decodeErrorData: dco_decode_payment_error, - ), - constMeta: kCrateBindingsBindingLiquidSdkPrepareReceiveOnchainConstMeta, - argValues: [that, req], - apiImpl: this, - )); - } - - TaskConstMeta get kCrateBindingsBindingLiquidSdkPrepareReceiveOnchainConstMeta => const TaskConstMeta( - debugName: "BindingLiquidSdk_prepare_receive_onchain", - argNames: ["that", "req"], - ); - - @override - Future crateBindingsBindingLiquidSdkPrepareReceivePayment( - {required BindingLiquidSdk that, required PrepareReceivePaymentRequest req}) { - return handler.executeNormal(NormalTask( - callFfi: (port_) { - var arg0 = - cst_encode_Auto_Ref_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerBindingLiquidSdk( - that); - var arg1 = cst_encode_box_autoadd_prepare_receive_payment_request(req); + var arg1 = cst_encode_box_autoadd_prepare_receive_request(req); return wire.wire__crate__bindings__BindingLiquidSdk_prepare_receive_payment(port_, arg0, arg1); }, codec: DcoCodec( - decodeSuccessData: dco_decode_prepare_receive_payment_response, + decodeSuccessData: dco_decode_prepare_receive_response, decodeErrorData: dco_decode_payment_error, ), constMeta: kCrateBindingsBindingLiquidSdkPrepareReceivePaymentConstMeta, @@ -732,32 +700,6 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { argNames: ["that", "req"], ); - @override - Future crateBindingsBindingLiquidSdkReceiveOnchain( - {required BindingLiquidSdk that, required PrepareReceiveOnchainResponse req}) { - return handler.executeNormal(NormalTask( - callFfi: (port_) { - var arg0 = - cst_encode_Auto_Ref_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerBindingLiquidSdk( - that); - var arg1 = cst_encode_box_autoadd_prepare_receive_onchain_response(req); - return wire.wire__crate__bindings__BindingLiquidSdk_receive_onchain(port_, arg0, arg1); - }, - codec: DcoCodec( - decodeSuccessData: dco_decode_receive_onchain_response, - decodeErrorData: dco_decode_payment_error, - ), - constMeta: kCrateBindingsBindingLiquidSdkReceiveOnchainConstMeta, - argValues: [that, req], - apiImpl: this, - )); - } - - TaskConstMeta get kCrateBindingsBindingLiquidSdkReceiveOnchainConstMeta => const TaskConstMeta( - debugName: "BindingLiquidSdk_receive_onchain", - argNames: ["that", "req"], - ); - @override Future crateBindingsBindingLiquidSdkReceivePayment( {required BindingLiquidSdk that, required ReceivePaymentRequest req}) { @@ -885,13 +827,13 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { @override Future crateBindingsBindingLiquidSdkSendPayment( - {required BindingLiquidSdk that, required PrepareSendResponse req}) { + {required BindingLiquidSdk that, required SendPaymentRequest req}) { return handler.executeNormal(NormalTask( callFfi: (port_) { var arg0 = cst_encode_Auto_Ref_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerBindingLiquidSdk( that); - var arg1 = cst_encode_box_autoadd_prepare_send_response(req); + var arg1 = cst_encode_box_autoadd_send_payment_request(req); return wire.wire__crate__bindings__BindingLiquidSdk_send_payment(port_, arg0, arg1); }, codec: DcoCodec( @@ -1335,6 +1277,12 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { return dco_decode_payment(raw); } + @protected + PaymentDetails dco_decode_box_autoadd_payment_details(dynamic raw) { + // Codec=Dco (DartCObject based), see doc to use other codecs + return dco_decode_payment_details(raw); + } + @protected PrepareBuyBitcoinRequest dco_decode_box_autoadd_prepare_buy_bitcoin_request(dynamic raw) { // Codec=Dco (DartCObject based), see doc to use other codecs @@ -1348,21 +1296,9 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { } @protected - PrepareReceiveOnchainRequest dco_decode_box_autoadd_prepare_receive_onchain_request(dynamic raw) { + PrepareReceiveRequest dco_decode_box_autoadd_prepare_receive_request(dynamic raw) { // Codec=Dco (DartCObject based), see doc to use other codecs - return dco_decode_prepare_receive_onchain_request(raw); - } - - @protected - PrepareReceiveOnchainResponse dco_decode_box_autoadd_prepare_receive_onchain_response(dynamic raw) { - // Codec=Dco (DartCObject based), see doc to use other codecs - return dco_decode_prepare_receive_onchain_response(raw); - } - - @protected - PrepareReceivePaymentRequest dco_decode_box_autoadd_prepare_receive_payment_request(dynamic raw) { - // Codec=Dco (DartCObject based), see doc to use other codecs - return dco_decode_prepare_receive_payment_request(raw); + return dco_decode_prepare_receive_request(raw); } @protected @@ -1377,12 +1313,6 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { return dco_decode_prepare_send_request(raw); } - @protected - PrepareSendResponse dco_decode_box_autoadd_prepare_send_response(dynamic raw) { - // Codec=Dco (DartCObject based), see doc to use other codecs - return dco_decode_prepare_send_response(raw); - } - @protected ReceivePaymentRequest dco_decode_box_autoadd_receive_payment_request(dynamic raw) { // Codec=Dco (DartCObject based), see doc to use other codecs @@ -1407,6 +1337,12 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { return dco_decode_sdk_event(raw); } + @protected + SendPaymentRequest dco_decode_box_autoadd_send_payment_request(dynamic raw) { + // Codec=Dco (DartCObject based), see doc to use other codecs + return dco_decode_send_payment_request(raw); + } + @protected SuccessActionProcessed dco_decode_box_autoadd_success_action_processed(dynamic raw) { // Codec=Dco (DartCObject based), see doc to use other codecs @@ -1449,7 +1385,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { final arr = raw as List; if (arr.length != 2) throw Exception('unexpected arr length: expect 2 but see ${arr.length}'); return BuyBitcoinRequest( - prepareRes: dco_decode_prepare_buy_bitcoin_response(arr[0]), + prepareResponse: dco_decode_prepare_buy_bitcoin_response(arr[0]), redirectUrl: dco_decode_opt_String(arr[1]), ); } @@ -2082,6 +2018,12 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { return raw == null ? null : dco_decode_box_autoadd_i_64(raw); } + @protected + PaymentDetails? dco_decode_opt_box_autoadd_payment_details(dynamic raw) { + // Codec=Dco (DartCObject based), see doc to use other codecs + return raw == null ? null : dco_decode_box_autoadd_payment_details(raw); + } + @protected SuccessActionProcessed? dco_decode_opt_box_autoadd_success_action_processed(dynamic raw) { // Codec=Dco (DartCObject based), see doc to use other codecs @@ -2119,7 +2061,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { if (arr.length != 2) throw Exception('unexpected arr length: expect 2 but see ${arr.length}'); return PayOnchainRequest( address: dco_decode_String(arr[0]), - prepareRes: dco_decode_prepare_pay_onchain_response(arr[1]), + prepareResponse: dco_decode_prepare_pay_onchain_response(arr[1]), ); } @@ -2127,23 +2069,49 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { Payment dco_decode_payment(dynamic raw) { // Codec=Dco (DartCObject based), see doc to use other codecs final arr = raw as List; - if (arr.length != 12) throw Exception('unexpected arr length: expect 12 but see ${arr.length}'); + if (arr.length != 8) throw Exception('unexpected arr length: expect 8 but see ${arr.length}'); return Payment( - txId: dco_decode_opt_String(arr[0]), - swapId: dco_decode_opt_String(arr[1]), + destination: dco_decode_opt_String(arr[0]), + txId: dco_decode_opt_String(arr[1]), timestamp: dco_decode_u_32(arr[2]), amountSat: dco_decode_u_64(arr[3]), feesSat: dco_decode_u_64(arr[4]), - preimage: dco_decode_opt_String(arr[5]), - bolt11: dco_decode_opt_String(arr[6]), - description: dco_decode_String(arr[7]), - refundTxId: dco_decode_opt_String(arr[8]), - refundTxAmountSat: dco_decode_opt_box_autoadd_u_64(arr[9]), - paymentType: dco_decode_payment_type(arr[10]), - status: dco_decode_payment_state(arr[11]), + paymentType: dco_decode_payment_type(arr[5]), + status: dco_decode_payment_state(arr[6]), + details: dco_decode_opt_box_autoadd_payment_details(arr[7]), ); } + @protected + PaymentDetails dco_decode_payment_details(dynamic raw) { + // Codec=Dco (DartCObject based), see doc to use other codecs + switch (raw[0]) { + case 0: + return PaymentDetails_Lightning( + swapId: dco_decode_String(raw[1]), + description: dco_decode_String(raw[2]), + preimage: dco_decode_opt_String(raw[3]), + bolt11: dco_decode_opt_String(raw[4]), + refundTxId: dco_decode_opt_String(raw[5]), + refundTxAmountSat: dco_decode_opt_box_autoadd_u_64(raw[6]), + ); + case 1: + return PaymentDetails_Liquid( + destination: dco_decode_String(raw[1]), + description: dco_decode_String(raw[2]), + ); + case 2: + return PaymentDetails_Bitcoin( + swapId: dco_decode_String(raw[1]), + description: dco_decode_String(raw[2]), + refundTxId: dco_decode_opt_String(raw[3]), + refundTxAmountSat: dco_decode_opt_box_autoadd_u_64(raw[4]), + ); + default: + throw Exception("unreachable"); + } + } + @protected PaymentError dco_decode_payment_error(dynamic raw) { // Codec=Dco (DartCObject based), see doc to use other codecs @@ -2157,45 +2125,53 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { case 3: return PaymentError_AmountOutOfRange(); case 4: - return PaymentError_Generic( + return PaymentError_AmountMissing( err: dco_decode_String(raw[1]), ); case 5: - return PaymentError_InvalidOrExpiredFees(); + return PaymentError_InvalidNetwork( + err: dco_decode_String(raw[1]), + ); case 6: - return PaymentError_InsufficientFunds(); + return PaymentError_Generic( + err: dco_decode_String(raw[1]), + ); case 7: + return PaymentError_InvalidOrExpiredFees(); + case 8: + return PaymentError_InsufficientFunds(); + case 9: return PaymentError_InvalidInvoice( err: dco_decode_String(raw[1]), ); - case 8: + case 10: return PaymentError_InvalidPreimage(); - case 9: + case 11: return PaymentError_LwkError( err: dco_decode_String(raw[1]), ); - case 10: - return PaymentError_PairsNotFound(); - case 11: - return PaymentError_PaymentTimeout(); case 12: - return PaymentError_PersistError(); + return PaymentError_PairsNotFound(); case 13: + return PaymentError_PaymentTimeout(); + case 14: + return PaymentError_PersistError(); + case 15: return PaymentError_ReceiveError( err: dco_decode_String(raw[1]), ); - case 14: + case 16: return PaymentError_Refunded( err: dco_decode_String(raw[1]), refundTxId: dco_decode_String(raw[2]), ); - case 15: + case 17: return PaymentError_SelfTransferNotSupported(); - case 16: + case 18: return PaymentError_SendError( err: dco_decode_String(raw[1]), ); - case 17: + case 19: return PaymentError_SignerError( err: dco_decode_String(raw[1]), ); @@ -2204,6 +2180,12 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { } } + @protected + PaymentMethod dco_decode_payment_method(dynamic raw) { + // Codec=Dco (DartCObject based), see doc to use other codecs + return PaymentMethod.values[raw as int]; + } + @protected PaymentState dco_decode_payment_state(dynamic raw) { // Codec=Dco (DartCObject based), see doc to use other codecs @@ -2263,44 +2245,25 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { } @protected - PrepareReceiveOnchainRequest dco_decode_prepare_receive_onchain_request(dynamic raw) { - // Codec=Dco (DartCObject based), see doc to use other codecs - final arr = raw as List; - if (arr.length != 1) throw Exception('unexpected arr length: expect 1 but see ${arr.length}'); - return PrepareReceiveOnchainRequest( - payerAmountSat: dco_decode_u_64(arr[0]), - ); - } - - @protected - PrepareReceiveOnchainResponse dco_decode_prepare_receive_onchain_response(dynamic raw) { + PrepareReceiveRequest dco_decode_prepare_receive_request(dynamic raw) { // Codec=Dco (DartCObject based), see doc to use other codecs final arr = raw as List; if (arr.length != 2) throw Exception('unexpected arr length: expect 2 but see ${arr.length}'); - return PrepareReceiveOnchainResponse( - payerAmountSat: dco_decode_u_64(arr[0]), - feesSat: dco_decode_u_64(arr[1]), + return PrepareReceiveRequest( + payerAmountSat: dco_decode_opt_box_autoadd_u_64(arr[0]), + paymentMethod: dco_decode_payment_method(arr[1]), ); } @protected - PrepareReceivePaymentRequest dco_decode_prepare_receive_payment_request(dynamic raw) { + PrepareReceiveResponse dco_decode_prepare_receive_response(dynamic raw) { // Codec=Dco (DartCObject based), see doc to use other codecs final arr = raw as List; - if (arr.length != 1) throw Exception('unexpected arr length: expect 1 but see ${arr.length}'); - return PrepareReceivePaymentRequest( - payerAmountSat: dco_decode_u_64(arr[0]), - ); - } - - @protected - PrepareReceivePaymentResponse dco_decode_prepare_receive_payment_response(dynamic raw) { - // Codec=Dco (DartCObject based), see doc to use other codecs - final arr = raw as List; - if (arr.length != 2) throw Exception('unexpected arr length: expect 2 but see ${arr.length}'); - return PrepareReceivePaymentResponse( - payerAmountSat: dco_decode_u_64(arr[0]), - feesSat: dco_decode_u_64(arr[1]), + if (arr.length != 3) throw Exception('unexpected arr length: expect 3 but see ${arr.length}'); + return PrepareReceiveResponse( + paymentMethod: dco_decode_payment_method(arr[0]), + payerAmountSat: dco_decode_opt_box_autoadd_u_64(arr[1]), + feesSat: dco_decode_u_64(arr[2]), ); } @@ -2332,9 +2295,10 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { PrepareSendRequest dco_decode_prepare_send_request(dynamic raw) { // Codec=Dco (DartCObject based), see doc to use other codecs final arr = raw as List; - if (arr.length != 1) throw Exception('unexpected arr length: expect 1 but see ${arr.length}'); + if (arr.length != 2) throw Exception('unexpected arr length: expect 2 but see ${arr.length}'); return PrepareSendRequest( - invoice: dco_decode_String(arr[0]), + destination: dco_decode_String(arr[0]), + amountSat: dco_decode_opt_box_autoadd_u_64(arr[1]), ); } @@ -2344,7 +2308,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { final arr = raw as List; if (arr.length != 2) throw Exception('unexpected arr length: expect 2 but see ${arr.length}'); return PrepareSendResponse( - invoice: dco_decode_String(arr[0]), + destination: dco_decode_send_destination(arr[0]), feesSat: dco_decode_u_64(arr[1]), ); } @@ -2360,17 +2324,6 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { ); } - @protected - ReceiveOnchainResponse dco_decode_receive_onchain_response(dynamic raw) { - // Codec=Dco (DartCObject based), see doc to use other codecs - final arr = raw as List; - if (arr.length != 2) throw Exception('unexpected arr length: expect 2 but see ${arr.length}'); - return ReceiveOnchainResponse( - address: dco_decode_String(arr[0]), - bip21: dco_decode_String(arr[1]), - ); - } - @protected ReceivePaymentRequest dco_decode_receive_payment_request(dynamic raw) { // Codec=Dco (DartCObject based), see doc to use other codecs @@ -2378,7 +2331,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { if (arr.length != 2) throw Exception('unexpected arr length: expect 2 but see ${arr.length}'); return ReceivePaymentRequest( description: dco_decode_opt_String(arr[0]), - prepareRes: dco_decode_prepare_receive_payment_response(arr[1]), + prepareResponse: dco_decode_prepare_receive_response(arr[1]), ); } @@ -2386,10 +2339,9 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { ReceivePaymentResponse dco_decode_receive_payment_response(dynamic raw) { // Codec=Dco (DartCObject based), see doc to use other codecs final arr = raw as List; - if (arr.length != 2) throw Exception('unexpected arr length: expect 2 but see ${arr.length}'); + if (arr.length != 1) throw Exception('unexpected arr length: expect 1 but see ${arr.length}'); return ReceivePaymentResponse( - id: dco_decode_String(arr[0]), - invoice: dco_decode_String(arr[1]), + destination: dco_decode_String(arr[0]), ); } @@ -2533,6 +2485,33 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { } } + @protected + SendDestination dco_decode_send_destination(dynamic raw) { + // Codec=Dco (DartCObject based), see doc to use other codecs + switch (raw[0]) { + case 0: + return SendDestination_LiquidAddress( + addressData: dco_decode_box_autoadd_liquid_address_data(raw[1]), + ); + case 1: + return SendDestination_Bolt11( + invoice: dco_decode_box_autoadd_ln_invoice(raw[1]), + ); + default: + throw Exception("unreachable"); + } + } + + @protected + SendPaymentRequest dco_decode_send_payment_request(dynamic raw) { + // Codec=Dco (DartCObject based), see doc to use other codecs + final arr = raw as List; + if (arr.length != 1) throw Exception('unexpected arr length: expect 1 but see ${arr.length}'); + return SendPaymentRequest( + prepareResponse: dco_decode_prepare_send_response(arr[0]), + ); + } + @protected SendPaymentResponse dco_decode_send_payment_response(dynamic raw) { // Codec=Dco (DartCObject based), see doc to use other codecs @@ -2884,6 +2863,12 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { return (sse_decode_payment(deserializer)); } + @protected + PaymentDetails sse_decode_box_autoadd_payment_details(SseDeserializer deserializer) { + // Codec=Sse (Serialization based), see doc to use other codecs + return (sse_decode_payment_details(deserializer)); + } + @protected PrepareBuyBitcoinRequest sse_decode_box_autoadd_prepare_buy_bitcoin_request(SseDeserializer deserializer) { // Codec=Sse (Serialization based), see doc to use other codecs @@ -2897,24 +2882,9 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { } @protected - PrepareReceiveOnchainRequest sse_decode_box_autoadd_prepare_receive_onchain_request( - SseDeserializer deserializer) { + PrepareReceiveRequest sse_decode_box_autoadd_prepare_receive_request(SseDeserializer deserializer) { // Codec=Sse (Serialization based), see doc to use other codecs - return (sse_decode_prepare_receive_onchain_request(deserializer)); - } - - @protected - PrepareReceiveOnchainResponse sse_decode_box_autoadd_prepare_receive_onchain_response( - SseDeserializer deserializer) { - // Codec=Sse (Serialization based), see doc to use other codecs - return (sse_decode_prepare_receive_onchain_response(deserializer)); - } - - @protected - PrepareReceivePaymentRequest sse_decode_box_autoadd_prepare_receive_payment_request( - SseDeserializer deserializer) { - // Codec=Sse (Serialization based), see doc to use other codecs - return (sse_decode_prepare_receive_payment_request(deserializer)); + return (sse_decode_prepare_receive_request(deserializer)); } @protected @@ -2929,12 +2899,6 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { return (sse_decode_prepare_send_request(deserializer)); } - @protected - PrepareSendResponse sse_decode_box_autoadd_prepare_send_response(SseDeserializer deserializer) { - // Codec=Sse (Serialization based), see doc to use other codecs - return (sse_decode_prepare_send_response(deserializer)); - } - @protected ReceivePaymentRequest sse_decode_box_autoadd_receive_payment_request(SseDeserializer deserializer) { // Codec=Sse (Serialization based), see doc to use other codecs @@ -2959,6 +2923,12 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { return (sse_decode_sdk_event(deserializer)); } + @protected + SendPaymentRequest sse_decode_box_autoadd_send_payment_request(SseDeserializer deserializer) { + // Codec=Sse (Serialization based), see doc to use other codecs + return (sse_decode_send_payment_request(deserializer)); + } + @protected SuccessActionProcessed sse_decode_box_autoadd_success_action_processed(SseDeserializer deserializer) { // Codec=Sse (Serialization based), see doc to use other codecs @@ -2999,9 +2969,9 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { @protected BuyBitcoinRequest sse_decode_buy_bitcoin_request(SseDeserializer deserializer) { // Codec=Sse (Serialization based), see doc to use other codecs - var var_prepareRes = sse_decode_prepare_buy_bitcoin_response(deserializer); + var var_prepareResponse = sse_decode_prepare_buy_bitcoin_response(deserializer); var var_redirectUrl = sse_decode_opt_String(deserializer); - return BuyBitcoinRequest(prepareRes: var_prepareRes, redirectUrl: var_redirectUrl); + return BuyBitcoinRequest(prepareResponse: var_prepareResponse, redirectUrl: var_redirectUrl); } @protected @@ -3671,6 +3641,17 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { } } + @protected + PaymentDetails? sse_decode_opt_box_autoadd_payment_details(SseDeserializer deserializer) { + // Codec=Sse (Serialization based), see doc to use other codecs + + if (sse_decode_bool(deserializer)) { + return (sse_decode_box_autoadd_payment_details(deserializer)); + } else { + return null; + } + } + @protected SuccessActionProcessed? sse_decode_opt_box_autoadd_success_action_processed(SseDeserializer deserializer) { // Codec=Sse (Serialization based), see doc to use other codecs @@ -3730,38 +3711,69 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { PayOnchainRequest sse_decode_pay_onchain_request(SseDeserializer deserializer) { // Codec=Sse (Serialization based), see doc to use other codecs var var_address = sse_decode_String(deserializer); - var var_prepareRes = sse_decode_prepare_pay_onchain_response(deserializer); - return PayOnchainRequest(address: var_address, prepareRes: var_prepareRes); + var var_prepareResponse = sse_decode_prepare_pay_onchain_response(deserializer); + return PayOnchainRequest(address: var_address, prepareResponse: var_prepareResponse); } @protected Payment sse_decode_payment(SseDeserializer deserializer) { // Codec=Sse (Serialization based), see doc to use other codecs + var var_destination = sse_decode_opt_String(deserializer); var var_txId = sse_decode_opt_String(deserializer); - var var_swapId = sse_decode_opt_String(deserializer); var var_timestamp = sse_decode_u_32(deserializer); var var_amountSat = sse_decode_u_64(deserializer); var var_feesSat = sse_decode_u_64(deserializer); - var var_preimage = sse_decode_opt_String(deserializer); - var var_bolt11 = sse_decode_opt_String(deserializer); - var var_description = sse_decode_String(deserializer); - var var_refundTxId = sse_decode_opt_String(deserializer); - var var_refundTxAmountSat = sse_decode_opt_box_autoadd_u_64(deserializer); var var_paymentType = sse_decode_payment_type(deserializer); var var_status = sse_decode_payment_state(deserializer); + var var_details = sse_decode_opt_box_autoadd_payment_details(deserializer); return Payment( + destination: var_destination, txId: var_txId, - swapId: var_swapId, timestamp: var_timestamp, amountSat: var_amountSat, feesSat: var_feesSat, - preimage: var_preimage, - bolt11: var_bolt11, - description: var_description, - refundTxId: var_refundTxId, - refundTxAmountSat: var_refundTxAmountSat, paymentType: var_paymentType, - status: var_status); + status: var_status, + details: var_details); + } + + @protected + PaymentDetails sse_decode_payment_details(SseDeserializer deserializer) { + // Codec=Sse (Serialization based), see doc to use other codecs + + var tag_ = sse_decode_i_32(deserializer); + switch (tag_) { + case 0: + var var_swapId = sse_decode_String(deserializer); + var var_description = sse_decode_String(deserializer); + var var_preimage = sse_decode_opt_String(deserializer); + var var_bolt11 = sse_decode_opt_String(deserializer); + var var_refundTxId = sse_decode_opt_String(deserializer); + var var_refundTxAmountSat = sse_decode_opt_box_autoadd_u_64(deserializer); + return PaymentDetails_Lightning( + swapId: var_swapId, + description: var_description, + preimage: var_preimage, + bolt11: var_bolt11, + refundTxId: var_refundTxId, + refundTxAmountSat: var_refundTxAmountSat); + case 1: + var var_destination = sse_decode_String(deserializer); + var var_description = sse_decode_String(deserializer); + return PaymentDetails_Liquid(destination: var_destination, description: var_description); + case 2: + var var_swapId = sse_decode_String(deserializer); + var var_description = sse_decode_String(deserializer); + var var_refundTxId = sse_decode_opt_String(deserializer); + var var_refundTxAmountSat = sse_decode_opt_box_autoadd_u_64(deserializer); + return PaymentDetails_Bitcoin( + swapId: var_swapId, + description: var_description, + refundTxId: var_refundTxId, + refundTxAmountSat: var_refundTxAmountSat); + default: + throw UnimplementedError(''); + } } @protected @@ -3780,38 +3792,44 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { return PaymentError_AmountOutOfRange(); case 4: var var_err = sse_decode_String(deserializer); - return PaymentError_Generic(err: var_err); + return PaymentError_AmountMissing(err: var_err); case 5: - return PaymentError_InvalidOrExpiredFees(); - case 6: - return PaymentError_InsufficientFunds(); - case 7: var var_err = sse_decode_String(deserializer); - return PaymentError_InvalidInvoice(err: var_err); + return PaymentError_InvalidNetwork(err: var_err); + case 6: + var var_err = sse_decode_String(deserializer); + return PaymentError_Generic(err: var_err); + case 7: + return PaymentError_InvalidOrExpiredFees(); case 8: - return PaymentError_InvalidPreimage(); + return PaymentError_InsufficientFunds(); case 9: var var_err = sse_decode_String(deserializer); - return PaymentError_LwkError(err: var_err); + return PaymentError_InvalidInvoice(err: var_err); case 10: - return PaymentError_PairsNotFound(); + return PaymentError_InvalidPreimage(); case 11: - return PaymentError_PaymentTimeout(); + var var_err = sse_decode_String(deserializer); + return PaymentError_LwkError(err: var_err); case 12: - return PaymentError_PersistError(); + return PaymentError_PairsNotFound(); case 13: + return PaymentError_PaymentTimeout(); + case 14: + return PaymentError_PersistError(); + case 15: var var_err = sse_decode_String(deserializer); return PaymentError_ReceiveError(err: var_err); - case 14: + case 16: var var_err = sse_decode_String(deserializer); var var_refundTxId = sse_decode_String(deserializer); return PaymentError_Refunded(err: var_err, refundTxId: var_refundTxId); - case 15: + case 17: return PaymentError_SelfTransferNotSupported(); - case 16: + case 18: var var_err = sse_decode_String(deserializer); return PaymentError_SendError(err: var_err); - case 17: + case 19: var var_err = sse_decode_String(deserializer); return PaymentError_SignerError(err: var_err); default: @@ -3819,6 +3837,13 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { } } + @protected + PaymentMethod sse_decode_payment_method(SseDeserializer deserializer) { + // Codec=Sse (Serialization based), see doc to use other codecs + var inner = sse_decode_i_32(deserializer); + return PaymentMethod.values[inner]; + } + @protected PaymentState sse_decode_payment_state(SseDeserializer deserializer) { // Codec=Sse (Serialization based), see doc to use other codecs @@ -3871,33 +3896,21 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { } @protected - PrepareReceiveOnchainRequest sse_decode_prepare_receive_onchain_request(SseDeserializer deserializer) { + PrepareReceiveRequest sse_decode_prepare_receive_request(SseDeserializer deserializer) { // Codec=Sse (Serialization based), see doc to use other codecs - var var_payerAmountSat = sse_decode_u_64(deserializer); - return PrepareReceiveOnchainRequest(payerAmountSat: var_payerAmountSat); + var var_payerAmountSat = sse_decode_opt_box_autoadd_u_64(deserializer); + var var_paymentMethod = sse_decode_payment_method(deserializer); + return PrepareReceiveRequest(payerAmountSat: var_payerAmountSat, paymentMethod: var_paymentMethod); } @protected - PrepareReceiveOnchainResponse sse_decode_prepare_receive_onchain_response(SseDeserializer deserializer) { + PrepareReceiveResponse sse_decode_prepare_receive_response(SseDeserializer deserializer) { // Codec=Sse (Serialization based), see doc to use other codecs - var var_payerAmountSat = sse_decode_u_64(deserializer); + var var_paymentMethod = sse_decode_payment_method(deserializer); + var var_payerAmountSat = sse_decode_opt_box_autoadd_u_64(deserializer); var var_feesSat = sse_decode_u_64(deserializer); - return PrepareReceiveOnchainResponse(payerAmountSat: var_payerAmountSat, feesSat: var_feesSat); - } - - @protected - PrepareReceivePaymentRequest sse_decode_prepare_receive_payment_request(SseDeserializer deserializer) { - // Codec=Sse (Serialization based), see doc to use other codecs - var var_payerAmountSat = sse_decode_u_64(deserializer); - return PrepareReceivePaymentRequest(payerAmountSat: var_payerAmountSat); - } - - @protected - PrepareReceivePaymentResponse sse_decode_prepare_receive_payment_response(SseDeserializer deserializer) { - // Codec=Sse (Serialization based), see doc to use other codecs - var var_payerAmountSat = sse_decode_u_64(deserializer); - var var_feesSat = sse_decode_u_64(deserializer); - return PrepareReceivePaymentResponse(payerAmountSat: var_payerAmountSat, feesSat: var_feesSat); + return PrepareReceiveResponse( + paymentMethod: var_paymentMethod, payerAmountSat: var_payerAmountSat, feesSat: var_feesSat); } @protected @@ -3922,16 +3935,17 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { @protected PrepareSendRequest sse_decode_prepare_send_request(SseDeserializer deserializer) { // Codec=Sse (Serialization based), see doc to use other codecs - var var_invoice = sse_decode_String(deserializer); - return PrepareSendRequest(invoice: var_invoice); + var var_destination = sse_decode_String(deserializer); + var var_amountSat = sse_decode_opt_box_autoadd_u_64(deserializer); + return PrepareSendRequest(destination: var_destination, amountSat: var_amountSat); } @protected PrepareSendResponse sse_decode_prepare_send_response(SseDeserializer deserializer) { // Codec=Sse (Serialization based), see doc to use other codecs - var var_invoice = sse_decode_String(deserializer); + var var_destination = sse_decode_send_destination(deserializer); var var_feesSat = sse_decode_u_64(deserializer); - return PrepareSendResponse(invoice: var_invoice, feesSat: var_feesSat); + return PrepareSendResponse(destination: var_destination, feesSat: var_feesSat); } @protected @@ -3942,28 +3956,19 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { return Rate(coin: var_coin, value: var_value); } - @protected - ReceiveOnchainResponse sse_decode_receive_onchain_response(SseDeserializer deserializer) { - // Codec=Sse (Serialization based), see doc to use other codecs - var var_address = sse_decode_String(deserializer); - var var_bip21 = sse_decode_String(deserializer); - return ReceiveOnchainResponse(address: var_address, bip21: var_bip21); - } - @protected ReceivePaymentRequest sse_decode_receive_payment_request(SseDeserializer deserializer) { // Codec=Sse (Serialization based), see doc to use other codecs var var_description = sse_decode_opt_String(deserializer); - var var_prepareRes = sse_decode_prepare_receive_payment_response(deserializer); - return ReceivePaymentRequest(description: var_description, prepareRes: var_prepareRes); + var var_prepareResponse = sse_decode_prepare_receive_response(deserializer); + return ReceivePaymentRequest(description: var_description, prepareResponse: var_prepareResponse); } @protected ReceivePaymentResponse sse_decode_receive_payment_response(SseDeserializer deserializer) { // Codec=Sse (Serialization based), see doc to use other codecs - var var_id = sse_decode_String(deserializer); - var var_invoice = sse_decode_String(deserializer); - return ReceivePaymentResponse(id: var_id, invoice: var_invoice); + var var_destination = sse_decode_String(deserializer); + return ReceivePaymentResponse(destination: var_destination); } @protected @@ -4094,6 +4099,30 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { } } + @protected + SendDestination sse_decode_send_destination(SseDeserializer deserializer) { + // Codec=Sse (Serialization based), see doc to use other codecs + + var tag_ = sse_decode_i_32(deserializer); + switch (tag_) { + case 0: + var var_addressData = sse_decode_box_autoadd_liquid_address_data(deserializer); + return SendDestination_LiquidAddress(addressData: var_addressData); + case 1: + var var_invoice = sse_decode_box_autoadd_ln_invoice(deserializer); + return SendDestination_Bolt11(invoice: var_invoice); + default: + throw UnimplementedError(''); + } + } + + @protected + SendPaymentRequest sse_decode_send_payment_request(SseDeserializer deserializer) { + // Codec=Sse (Serialization based), see doc to use other codecs + var var_prepareResponse = sse_decode_prepare_send_response(deserializer); + return SendPaymentRequest(prepareResponse: var_prepareResponse); + } + @protected SendPaymentResponse sse_decode_send_payment_response(SseDeserializer deserializer) { // Codec=Sse (Serialization based), see doc to use other codecs @@ -4236,6 +4265,12 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { return cst_encode_i_32(raw.index); } + @protected + int cst_encode_payment_method(PaymentMethod raw) { + // Codec=Cst (C-struct based), see doc to use other codecs + return cst_encode_i_32(raw.index); + } + @protected int cst_encode_payment_state(PaymentState raw) { // Codec=Cst (C-struct based), see doc to use other codecs @@ -4529,6 +4564,12 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { sse_encode_payment(self, serializer); } + @protected + void sse_encode_box_autoadd_payment_details(PaymentDetails self, SseSerializer serializer) { + // Codec=Sse (Serialization based), see doc to use other codecs + sse_encode_payment_details(self, serializer); + } + @protected void sse_encode_box_autoadd_prepare_buy_bitcoin_request( PrepareBuyBitcoinRequest self, SseSerializer serializer) { @@ -4544,24 +4585,9 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { } @protected - void sse_encode_box_autoadd_prepare_receive_onchain_request( - PrepareReceiveOnchainRequest self, SseSerializer serializer) { + void sse_encode_box_autoadd_prepare_receive_request(PrepareReceiveRequest self, SseSerializer serializer) { // Codec=Sse (Serialization based), see doc to use other codecs - sse_encode_prepare_receive_onchain_request(self, serializer); - } - - @protected - void sse_encode_box_autoadd_prepare_receive_onchain_response( - PrepareReceiveOnchainResponse self, SseSerializer serializer) { - // Codec=Sse (Serialization based), see doc to use other codecs - sse_encode_prepare_receive_onchain_response(self, serializer); - } - - @protected - void sse_encode_box_autoadd_prepare_receive_payment_request( - PrepareReceivePaymentRequest self, SseSerializer serializer) { - // Codec=Sse (Serialization based), see doc to use other codecs - sse_encode_prepare_receive_payment_request(self, serializer); + sse_encode_prepare_receive_request(self, serializer); } @protected @@ -4576,12 +4602,6 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { sse_encode_prepare_send_request(self, serializer); } - @protected - void sse_encode_box_autoadd_prepare_send_response(PrepareSendResponse self, SseSerializer serializer) { - // Codec=Sse (Serialization based), see doc to use other codecs - sse_encode_prepare_send_response(self, serializer); - } - @protected void sse_encode_box_autoadd_receive_payment_request(ReceivePaymentRequest self, SseSerializer serializer) { // Codec=Sse (Serialization based), see doc to use other codecs @@ -4606,6 +4626,12 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { sse_encode_sdk_event(self, serializer); } + @protected + void sse_encode_box_autoadd_send_payment_request(SendPaymentRequest self, SseSerializer serializer) { + // Codec=Sse (Serialization based), see doc to use other codecs + sse_encode_send_payment_request(self, serializer); + } + @protected void sse_encode_box_autoadd_success_action_processed( SuccessActionProcessed self, SseSerializer serializer) { @@ -4646,7 +4672,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { @protected void sse_encode_buy_bitcoin_request(BuyBitcoinRequest self, SseSerializer serializer) { // Codec=Sse (Serialization based), see doc to use other codecs - sse_encode_prepare_buy_bitcoin_response(self.prepareRes, serializer); + sse_encode_prepare_buy_bitcoin_response(self.prepareResponse, serializer); sse_encode_opt_String(self.redirectUrl, serializer); } @@ -5188,6 +5214,16 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { } } + @protected + void sse_encode_opt_box_autoadd_payment_details(PaymentDetails? self, SseSerializer serializer) { + // Codec=Sse (Serialization based), see doc to use other codecs + + sse_encode_bool(self != null, serializer); + if (self != null) { + sse_encode_box_autoadd_payment_details(self, serializer); + } + } + @protected void sse_encode_opt_box_autoadd_success_action_processed( SuccessActionProcessed? self, SseSerializer serializer) { @@ -5243,24 +5279,59 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { void sse_encode_pay_onchain_request(PayOnchainRequest self, SseSerializer serializer) { // Codec=Sse (Serialization based), see doc to use other codecs sse_encode_String(self.address, serializer); - sse_encode_prepare_pay_onchain_response(self.prepareRes, serializer); + sse_encode_prepare_pay_onchain_response(self.prepareResponse, serializer); } @protected void sse_encode_payment(Payment self, SseSerializer serializer) { // Codec=Sse (Serialization based), see doc to use other codecs + sse_encode_opt_String(self.destination, serializer); sse_encode_opt_String(self.txId, serializer); - sse_encode_opt_String(self.swapId, serializer); sse_encode_u_32(self.timestamp, serializer); sse_encode_u_64(self.amountSat, serializer); sse_encode_u_64(self.feesSat, serializer); - sse_encode_opt_String(self.preimage, serializer); - sse_encode_opt_String(self.bolt11, serializer); - sse_encode_String(self.description, serializer); - sse_encode_opt_String(self.refundTxId, serializer); - sse_encode_opt_box_autoadd_u_64(self.refundTxAmountSat, serializer); sse_encode_payment_type(self.paymentType, serializer); sse_encode_payment_state(self.status, serializer); + sse_encode_opt_box_autoadd_payment_details(self.details, serializer); + } + + @protected + void sse_encode_payment_details(PaymentDetails self, SseSerializer serializer) { + // Codec=Sse (Serialization based), see doc to use other codecs + switch (self) { + case PaymentDetails_Lightning( + swapId: final swapId, + description: final description, + preimage: final preimage, + bolt11: final bolt11, + refundTxId: final refundTxId, + refundTxAmountSat: final refundTxAmountSat + ): + sse_encode_i_32(0, serializer); + sse_encode_String(swapId, serializer); + sse_encode_String(description, serializer); + sse_encode_opt_String(preimage, serializer); + sse_encode_opt_String(bolt11, serializer); + sse_encode_opt_String(refundTxId, serializer); + sse_encode_opt_box_autoadd_u_64(refundTxAmountSat, serializer); + case PaymentDetails_Liquid(destination: final destination, description: final description): + sse_encode_i_32(1, serializer); + sse_encode_String(destination, serializer); + sse_encode_String(description, serializer); + case PaymentDetails_Bitcoin( + swapId: final swapId, + description: final description, + refundTxId: final refundTxId, + refundTxAmountSat: final refundTxAmountSat + ): + sse_encode_i_32(2, serializer); + sse_encode_String(swapId, serializer); + sse_encode_String(description, serializer); + sse_encode_opt_String(refundTxId, serializer); + sse_encode_opt_box_autoadd_u_64(refundTxAmountSat, serializer); + default: + throw UnimplementedError(''); + } } @protected @@ -5275,47 +5346,59 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { sse_encode_i_32(2, serializer); case PaymentError_AmountOutOfRange(): sse_encode_i_32(3, serializer); - case PaymentError_Generic(err: final err): + case PaymentError_AmountMissing(err: final err): sse_encode_i_32(4, serializer); sse_encode_String(err, serializer); - case PaymentError_InvalidOrExpiredFees(): + case PaymentError_InvalidNetwork(err: final err): sse_encode_i_32(5, serializer); - case PaymentError_InsufficientFunds(): - sse_encode_i_32(6, serializer); - case PaymentError_InvalidInvoice(err: final err): - sse_encode_i_32(7, serializer); sse_encode_String(err, serializer); - case PaymentError_InvalidPreimage(): + case PaymentError_Generic(err: final err): + sse_encode_i_32(6, serializer); + sse_encode_String(err, serializer); + case PaymentError_InvalidOrExpiredFees(): + sse_encode_i_32(7, serializer); + case PaymentError_InsufficientFunds(): sse_encode_i_32(8, serializer); - case PaymentError_LwkError(err: final err): + case PaymentError_InvalidInvoice(err: final err): sse_encode_i_32(9, serializer); sse_encode_String(err, serializer); - case PaymentError_PairsNotFound(): + case PaymentError_InvalidPreimage(): sse_encode_i_32(10, serializer); - case PaymentError_PaymentTimeout(): + case PaymentError_LwkError(err: final err): sse_encode_i_32(11, serializer); - case PaymentError_PersistError(): + sse_encode_String(err, serializer); + case PaymentError_PairsNotFound(): sse_encode_i_32(12, serializer); - case PaymentError_ReceiveError(err: final err): + case PaymentError_PaymentTimeout(): sse_encode_i_32(13, serializer); + case PaymentError_PersistError(): + sse_encode_i_32(14, serializer); + case PaymentError_ReceiveError(err: final err): + sse_encode_i_32(15, serializer); sse_encode_String(err, serializer); case PaymentError_Refunded(err: final err, refundTxId: final refundTxId): - sse_encode_i_32(14, serializer); + sse_encode_i_32(16, serializer); sse_encode_String(err, serializer); sse_encode_String(refundTxId, serializer); case PaymentError_SelfTransferNotSupported(): - sse_encode_i_32(15, serializer); + sse_encode_i_32(17, serializer); case PaymentError_SendError(err: final err): - sse_encode_i_32(16, serializer); + sse_encode_i_32(18, serializer); sse_encode_String(err, serializer); case PaymentError_SignerError(err: final err): - sse_encode_i_32(17, serializer); + sse_encode_i_32(19, serializer); sse_encode_String(err, serializer); default: throw UnimplementedError(''); } } + @protected + void sse_encode_payment_method(PaymentMethod self, SseSerializer serializer) { + // Codec=Sse (Serialization based), see doc to use other codecs + sse_encode_i_32(self.index, serializer); + } + @protected void sse_encode_payment_state(PaymentState self, SseSerializer serializer) { // Codec=Sse (Serialization based), see doc to use other codecs @@ -5359,32 +5442,17 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { } @protected - void sse_encode_prepare_receive_onchain_request( - PrepareReceiveOnchainRequest self, SseSerializer serializer) { + void sse_encode_prepare_receive_request(PrepareReceiveRequest self, SseSerializer serializer) { // Codec=Sse (Serialization based), see doc to use other codecs - sse_encode_u_64(self.payerAmountSat, serializer); + sse_encode_opt_box_autoadd_u_64(self.payerAmountSat, serializer); + sse_encode_payment_method(self.paymentMethod, serializer); } @protected - void sse_encode_prepare_receive_onchain_response( - PrepareReceiveOnchainResponse self, SseSerializer serializer) { + void sse_encode_prepare_receive_response(PrepareReceiveResponse self, SseSerializer serializer) { // Codec=Sse (Serialization based), see doc to use other codecs - sse_encode_u_64(self.payerAmountSat, serializer); - sse_encode_u_64(self.feesSat, serializer); - } - - @protected - void sse_encode_prepare_receive_payment_request( - PrepareReceivePaymentRequest self, SseSerializer serializer) { - // Codec=Sse (Serialization based), see doc to use other codecs - sse_encode_u_64(self.payerAmountSat, serializer); - } - - @protected - void sse_encode_prepare_receive_payment_response( - PrepareReceivePaymentResponse self, SseSerializer serializer) { - // Codec=Sse (Serialization based), see doc to use other codecs - sse_encode_u_64(self.payerAmountSat, serializer); + sse_encode_payment_method(self.paymentMethod, serializer); + sse_encode_opt_box_autoadd_u_64(self.payerAmountSat, serializer); sse_encode_u_64(self.feesSat, serializer); } @@ -5407,13 +5475,14 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { @protected void sse_encode_prepare_send_request(PrepareSendRequest self, SseSerializer serializer) { // Codec=Sse (Serialization based), see doc to use other codecs - sse_encode_String(self.invoice, serializer); + sse_encode_String(self.destination, serializer); + sse_encode_opt_box_autoadd_u_64(self.amountSat, serializer); } @protected void sse_encode_prepare_send_response(PrepareSendResponse self, SseSerializer serializer) { // Codec=Sse (Serialization based), see doc to use other codecs - sse_encode_String(self.invoice, serializer); + sse_encode_send_destination(self.destination, serializer); sse_encode_u_64(self.feesSat, serializer); } @@ -5424,25 +5493,17 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { sse_encode_f_64(self.value, serializer); } - @protected - void sse_encode_receive_onchain_response(ReceiveOnchainResponse self, SseSerializer serializer) { - // Codec=Sse (Serialization based), see doc to use other codecs - sse_encode_String(self.address, serializer); - sse_encode_String(self.bip21, serializer); - } - @protected void sse_encode_receive_payment_request(ReceivePaymentRequest self, SseSerializer serializer) { // Codec=Sse (Serialization based), see doc to use other codecs sse_encode_opt_String(self.description, serializer); - sse_encode_prepare_receive_payment_response(self.prepareRes, serializer); + sse_encode_prepare_receive_response(self.prepareResponse, serializer); } @protected void sse_encode_receive_payment_response(ReceivePaymentResponse self, SseSerializer serializer) { // Codec=Sse (Serialization based), see doc to use other codecs - sse_encode_String(self.id, serializer); - sse_encode_String(self.invoice, serializer); + sse_encode_String(self.destination, serializer); } @protected @@ -5549,6 +5610,27 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { } } + @protected + void sse_encode_send_destination(SendDestination self, SseSerializer serializer) { + // Codec=Sse (Serialization based), see doc to use other codecs + switch (self) { + case SendDestination_LiquidAddress(addressData: final addressData): + sse_encode_i_32(0, serializer); + sse_encode_box_autoadd_liquid_address_data(addressData, serializer); + case SendDestination_Bolt11(invoice: final invoice): + sse_encode_i_32(1, serializer); + sse_encode_box_autoadd_ln_invoice(invoice, serializer); + default: + throw UnimplementedError(''); + } + } + + @protected + void sse_encode_send_payment_request(SendPaymentRequest self, SseSerializer serializer) { + // Codec=Sse (Serialization based), see doc to use other codecs + sse_encode_prepare_send_response(self.prepareResponse, serializer); + } + @protected void sse_encode_send_payment_response(SendPaymentResponse self, SseSerializer serializer) { // Codec=Sse (Serialization based), see doc to use other codecs @@ -5709,10 +5791,7 @@ class BindingLiquidSdkImpl extends RustOpaque implements BindingLiquidSdk { Future preparePayOnchain({required PreparePayOnchainRequest req}) => RustLib.instance.api.crateBindingsBindingLiquidSdkPreparePayOnchain(that: this, req: req); - Future prepareReceiveOnchain({required PrepareReceiveOnchainRequest req}) => - RustLib.instance.api.crateBindingsBindingLiquidSdkPrepareReceiveOnchain(that: this, req: req); - - Future prepareReceivePayment({required PrepareReceivePaymentRequest req}) => + Future prepareReceivePayment({required PrepareReceiveRequest req}) => RustLib.instance.api.crateBindingsBindingLiquidSdkPrepareReceivePayment(that: this, req: req); Future prepareRefund({required PrepareRefundRequest req}) => @@ -5721,9 +5800,6 @@ class BindingLiquidSdkImpl extends RustOpaque implements BindingLiquidSdk { Future prepareSendPayment({required PrepareSendRequest req}) => RustLib.instance.api.crateBindingsBindingLiquidSdkPrepareSendPayment(that: this, req: req); - Future receiveOnchain({required PrepareReceiveOnchainResponse req}) => - RustLib.instance.api.crateBindingsBindingLiquidSdkReceiveOnchain(that: this, req: req); - Future receivePayment({required ReceivePaymentRequest req}) => RustLib.instance.api.crateBindingsBindingLiquidSdkReceivePayment(that: this, req: req); @@ -5742,7 +5818,7 @@ class BindingLiquidSdkImpl extends RustOpaque implements BindingLiquidSdk { void restore({required RestoreRequest req}) => RustLib.instance.api.crateBindingsBindingLiquidSdkRestore(that: this, req: req); - Future sendPayment({required PrepareSendResponse req}) => + Future sendPayment({required SendPaymentRequest req}) => RustLib.instance.api.crateBindingsBindingLiquidSdkSendPayment(that: this, req: req); Future sync() => RustLib.instance.api.crateBindingsBindingLiquidSdkSync( diff --git a/packages/dart/lib/src/frb_generated.io.dart b/packages/dart/lib/src/frb_generated.io.dart index 8d62266..cdcff6d 100644 --- a/packages/dart/lib/src/frb_generated.io.dart +++ b/packages/dart/lib/src/frb_generated.io.dart @@ -140,6 +140,9 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl { @protected Payment dco_decode_box_autoadd_payment(dynamic raw); + @protected + PaymentDetails dco_decode_box_autoadd_payment_details(dynamic raw); + @protected PrepareBuyBitcoinRequest dco_decode_box_autoadd_prepare_buy_bitcoin_request(dynamic raw); @@ -147,13 +150,7 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl { PreparePayOnchainRequest dco_decode_box_autoadd_prepare_pay_onchain_request(dynamic raw); @protected - PrepareReceiveOnchainRequest dco_decode_box_autoadd_prepare_receive_onchain_request(dynamic raw); - - @protected - PrepareReceiveOnchainResponse dco_decode_box_autoadd_prepare_receive_onchain_response(dynamic raw); - - @protected - PrepareReceivePaymentRequest dco_decode_box_autoadd_prepare_receive_payment_request(dynamic raw); + PrepareReceiveRequest dco_decode_box_autoadd_prepare_receive_request(dynamic raw); @protected PrepareRefundRequest dco_decode_box_autoadd_prepare_refund_request(dynamic raw); @@ -161,9 +158,6 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl { @protected PrepareSendRequest dco_decode_box_autoadd_prepare_send_request(dynamic raw); - @protected - PrepareSendResponse dco_decode_box_autoadd_prepare_send_response(dynamic raw); - @protected ReceivePaymentRequest dco_decode_box_autoadd_receive_payment_request(dynamic raw); @@ -176,6 +170,9 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl { @protected SdkEvent dco_decode_box_autoadd_sdk_event(dynamic raw); + @protected + SendPaymentRequest dco_decode_box_autoadd_send_payment_request(dynamic raw); + @protected SuccessActionProcessed dco_decode_box_autoadd_success_action_processed(dynamic raw); @@ -344,6 +341,9 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl { @protected PlatformInt64? dco_decode_opt_box_autoadd_i_64(dynamic raw); + @protected + PaymentDetails? dco_decode_opt_box_autoadd_payment_details(dynamic raw); + @protected SuccessActionProcessed? dco_decode_opt_box_autoadd_success_action_processed(dynamic raw); @@ -365,9 +365,15 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl { @protected Payment dco_decode_payment(dynamic raw); + @protected + PaymentDetails dco_decode_payment_details(dynamic raw); + @protected PaymentError dco_decode_payment_error(dynamic raw); + @protected + PaymentMethod dco_decode_payment_method(dynamic raw); + @protected PaymentState dco_decode_payment_state(dynamic raw); @@ -387,16 +393,10 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl { PreparePayOnchainResponse dco_decode_prepare_pay_onchain_response(dynamic raw); @protected - PrepareReceiveOnchainRequest dco_decode_prepare_receive_onchain_request(dynamic raw); + PrepareReceiveRequest dco_decode_prepare_receive_request(dynamic raw); @protected - PrepareReceiveOnchainResponse dco_decode_prepare_receive_onchain_response(dynamic raw); - - @protected - PrepareReceivePaymentRequest dco_decode_prepare_receive_payment_request(dynamic raw); - - @protected - PrepareReceivePaymentResponse dco_decode_prepare_receive_payment_response(dynamic raw); + PrepareReceiveResponse dco_decode_prepare_receive_response(dynamic raw); @protected PrepareRefundRequest dco_decode_prepare_refund_request(dynamic raw); @@ -413,9 +413,6 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl { @protected Rate dco_decode_rate(dynamic raw); - @protected - ReceiveOnchainResponse dco_decode_receive_onchain_response(dynamic raw); - @protected ReceivePaymentRequest dco_decode_receive_payment_request(dynamic raw); @@ -449,6 +446,12 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl { @protected SdkEvent dco_decode_sdk_event(dynamic raw); + @protected + SendDestination dco_decode_send_destination(dynamic raw); + + @protected + SendPaymentRequest dco_decode_send_payment_request(dynamic raw); + @protected SendPaymentResponse dco_decode_send_payment_response(dynamic raw); @@ -597,6 +600,9 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl { @protected Payment sse_decode_box_autoadd_payment(SseDeserializer deserializer); + @protected + PaymentDetails sse_decode_box_autoadd_payment_details(SseDeserializer deserializer); + @protected PrepareBuyBitcoinRequest sse_decode_box_autoadd_prepare_buy_bitcoin_request(SseDeserializer deserializer); @@ -604,16 +610,7 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl { PreparePayOnchainRequest sse_decode_box_autoadd_prepare_pay_onchain_request(SseDeserializer deserializer); @protected - PrepareReceiveOnchainRequest sse_decode_box_autoadd_prepare_receive_onchain_request( - SseDeserializer deserializer); - - @protected - PrepareReceiveOnchainResponse sse_decode_box_autoadd_prepare_receive_onchain_response( - SseDeserializer deserializer); - - @protected - PrepareReceivePaymentRequest sse_decode_box_autoadd_prepare_receive_payment_request( - SseDeserializer deserializer); + PrepareReceiveRequest sse_decode_box_autoadd_prepare_receive_request(SseDeserializer deserializer); @protected PrepareRefundRequest sse_decode_box_autoadd_prepare_refund_request(SseDeserializer deserializer); @@ -621,9 +618,6 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl { @protected PrepareSendRequest sse_decode_box_autoadd_prepare_send_request(SseDeserializer deserializer); - @protected - PrepareSendResponse sse_decode_box_autoadd_prepare_send_response(SseDeserializer deserializer); - @protected ReceivePaymentRequest sse_decode_box_autoadd_receive_payment_request(SseDeserializer deserializer); @@ -636,6 +630,9 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl { @protected SdkEvent sse_decode_box_autoadd_sdk_event(SseDeserializer deserializer); + @protected + SendPaymentRequest sse_decode_box_autoadd_send_payment_request(SseDeserializer deserializer); + @protected SuccessActionProcessed sse_decode_box_autoadd_success_action_processed(SseDeserializer deserializer); @@ -804,6 +801,9 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl { @protected PlatformInt64? sse_decode_opt_box_autoadd_i_64(SseDeserializer deserializer); + @protected + PaymentDetails? sse_decode_opt_box_autoadd_payment_details(SseDeserializer deserializer); + @protected SuccessActionProcessed? sse_decode_opt_box_autoadd_success_action_processed(SseDeserializer deserializer); @@ -825,9 +825,15 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl { @protected Payment sse_decode_payment(SseDeserializer deserializer); + @protected + PaymentDetails sse_decode_payment_details(SseDeserializer deserializer); + @protected PaymentError sse_decode_payment_error(SseDeserializer deserializer); + @protected + PaymentMethod sse_decode_payment_method(SseDeserializer deserializer); + @protected PaymentState sse_decode_payment_state(SseDeserializer deserializer); @@ -847,16 +853,10 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl { PreparePayOnchainResponse sse_decode_prepare_pay_onchain_response(SseDeserializer deserializer); @protected - PrepareReceiveOnchainRequest sse_decode_prepare_receive_onchain_request(SseDeserializer deserializer); + PrepareReceiveRequest sse_decode_prepare_receive_request(SseDeserializer deserializer); @protected - PrepareReceiveOnchainResponse sse_decode_prepare_receive_onchain_response(SseDeserializer deserializer); - - @protected - PrepareReceivePaymentRequest sse_decode_prepare_receive_payment_request(SseDeserializer deserializer); - - @protected - PrepareReceivePaymentResponse sse_decode_prepare_receive_payment_response(SseDeserializer deserializer); + PrepareReceiveResponse sse_decode_prepare_receive_response(SseDeserializer deserializer); @protected PrepareRefundRequest sse_decode_prepare_refund_request(SseDeserializer deserializer); @@ -873,9 +873,6 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl { @protected Rate sse_decode_rate(SseDeserializer deserializer); - @protected - ReceiveOnchainResponse sse_decode_receive_onchain_response(SseDeserializer deserializer); - @protected ReceivePaymentRequest sse_decode_receive_payment_request(SseDeserializer deserializer); @@ -909,6 +906,12 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl { @protected SdkEvent sse_decode_sdk_event(SseDeserializer deserializer); + @protected + SendDestination sse_decode_send_destination(SseDeserializer deserializer); + + @protected + SendPaymentRequest sse_decode_send_payment_request(SseDeserializer deserializer); + @protected SendPaymentResponse sse_decode_send_payment_response(SseDeserializer deserializer); @@ -1177,6 +1180,14 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl { return ptr; } + @protected + ffi.Pointer cst_encode_box_autoadd_payment_details(PaymentDetails raw) { + // Codec=Cst (C-struct based), see doc to use other codecs + final ptr = wire.cst_new_box_autoadd_payment_details(); + cst_api_fill_to_wire_payment_details(raw, ptr.ref); + return ptr; + } + @protected ffi.Pointer cst_encode_box_autoadd_prepare_buy_bitcoin_request( PrepareBuyBitcoinRequest raw) { @@ -1196,29 +1207,11 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl { } @protected - ffi.Pointer - cst_encode_box_autoadd_prepare_receive_onchain_request(PrepareReceiveOnchainRequest raw) { + ffi.Pointer cst_encode_box_autoadd_prepare_receive_request( + PrepareReceiveRequest raw) { // Codec=Cst (C-struct based), see doc to use other codecs - final ptr = wire.cst_new_box_autoadd_prepare_receive_onchain_request(); - cst_api_fill_to_wire_prepare_receive_onchain_request(raw, ptr.ref); - return ptr; - } - - @protected - ffi.Pointer - cst_encode_box_autoadd_prepare_receive_onchain_response(PrepareReceiveOnchainResponse raw) { - // Codec=Cst (C-struct based), see doc to use other codecs - final ptr = wire.cst_new_box_autoadd_prepare_receive_onchain_response(); - cst_api_fill_to_wire_prepare_receive_onchain_response(raw, ptr.ref); - return ptr; - } - - @protected - ffi.Pointer - cst_encode_box_autoadd_prepare_receive_payment_request(PrepareReceivePaymentRequest raw) { - // Codec=Cst (C-struct based), see doc to use other codecs - final ptr = wire.cst_new_box_autoadd_prepare_receive_payment_request(); - cst_api_fill_to_wire_prepare_receive_payment_request(raw, ptr.ref); + final ptr = wire.cst_new_box_autoadd_prepare_receive_request(); + cst_api_fill_to_wire_prepare_receive_request(raw, ptr.ref); return ptr; } @@ -1240,15 +1233,6 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl { return ptr; } - @protected - ffi.Pointer cst_encode_box_autoadd_prepare_send_response( - PrepareSendResponse raw) { - // Codec=Cst (C-struct based), see doc to use other codecs - final ptr = wire.cst_new_box_autoadd_prepare_send_response(); - cst_api_fill_to_wire_prepare_send_response(raw, ptr.ref); - return ptr; - } - @protected ffi.Pointer cst_encode_box_autoadd_receive_payment_request( ReceivePaymentRequest raw) { @@ -1282,6 +1266,15 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl { return ptr; } + @protected + ffi.Pointer cst_encode_box_autoadd_send_payment_request( + SendPaymentRequest raw) { + // Codec=Cst (C-struct based), see doc to use other codecs + final ptr = wire.cst_new_box_autoadd_send_payment_request(); + cst_api_fill_to_wire_send_payment_request(raw, ptr.ref); + return ptr; + } + @protected ffi.Pointer cst_encode_box_autoadd_success_action_processed( SuccessActionProcessed raw) { @@ -1442,6 +1435,12 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl { return raw == null ? ffi.nullptr : cst_encode_box_autoadd_i_64(raw); } + @protected + ffi.Pointer cst_encode_opt_box_autoadd_payment_details(PaymentDetails? raw) { + // Codec=Cst (C-struct based), see doc to use other codecs + return raw == null ? ffi.nullptr : cst_encode_box_autoadd_payment_details(raw); + } + @protected ffi.Pointer cst_encode_opt_box_autoadd_success_action_processed( SuccessActionProcessed? raw) { @@ -1661,6 +1660,12 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl { cst_api_fill_to_wire_payment(apiObj, wireObj.ref); } + @protected + void cst_api_fill_to_wire_box_autoadd_payment_details( + PaymentDetails apiObj, ffi.Pointer wireObj) { + cst_api_fill_to_wire_payment_details(apiObj, wireObj.ref); + } + @protected void cst_api_fill_to_wire_box_autoadd_prepare_buy_bitcoin_request( PrepareBuyBitcoinRequest apiObj, ffi.Pointer wireObj) { @@ -1674,21 +1679,9 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl { } @protected - void cst_api_fill_to_wire_box_autoadd_prepare_receive_onchain_request( - PrepareReceiveOnchainRequest apiObj, ffi.Pointer wireObj) { - cst_api_fill_to_wire_prepare_receive_onchain_request(apiObj, wireObj.ref); - } - - @protected - void cst_api_fill_to_wire_box_autoadd_prepare_receive_onchain_response( - PrepareReceiveOnchainResponse apiObj, ffi.Pointer wireObj) { - cst_api_fill_to_wire_prepare_receive_onchain_response(apiObj, wireObj.ref); - } - - @protected - void cst_api_fill_to_wire_box_autoadd_prepare_receive_payment_request( - PrepareReceivePaymentRequest apiObj, ffi.Pointer wireObj) { - cst_api_fill_to_wire_prepare_receive_payment_request(apiObj, wireObj.ref); + void cst_api_fill_to_wire_box_autoadd_prepare_receive_request( + PrepareReceiveRequest apiObj, ffi.Pointer wireObj) { + cst_api_fill_to_wire_prepare_receive_request(apiObj, wireObj.ref); } @protected @@ -1703,12 +1696,6 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl { cst_api_fill_to_wire_prepare_send_request(apiObj, wireObj.ref); } - @protected - void cst_api_fill_to_wire_box_autoadd_prepare_send_response( - PrepareSendResponse apiObj, ffi.Pointer wireObj) { - cst_api_fill_to_wire_prepare_send_response(apiObj, wireObj.ref); - } - @protected void cst_api_fill_to_wire_box_autoadd_receive_payment_request( ReceivePaymentRequest apiObj, ffi.Pointer wireObj) { @@ -1732,6 +1719,12 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl { cst_api_fill_to_wire_sdk_event(apiObj, wireObj.ref); } + @protected + void cst_api_fill_to_wire_box_autoadd_send_payment_request( + SendPaymentRequest apiObj, ffi.Pointer wireObj) { + cst_api_fill_to_wire_send_payment_request(apiObj, wireObj.ref); + } + @protected void cst_api_fill_to_wire_box_autoadd_success_action_processed( SuccessActionProcessed apiObj, ffi.Pointer wireObj) { @@ -1752,7 +1745,7 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl { @protected void cst_api_fill_to_wire_buy_bitcoin_request( BuyBitcoinRequest apiObj, wire_cst_buy_bitcoin_request wireObj) { - cst_api_fill_to_wire_prepare_buy_bitcoin_response(apiObj.prepareRes, wireObj.prepare_res); + cst_api_fill_to_wire_prepare_buy_bitcoin_response(apiObj.prepareResponse, wireObj.prepare_response); wireObj.redirect_url = cst_encode_opt_String(apiObj.redirectUrl); } @@ -2216,23 +2209,59 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl { void cst_api_fill_to_wire_pay_onchain_request( PayOnchainRequest apiObj, wire_cst_pay_onchain_request wireObj) { wireObj.address = cst_encode_String(apiObj.address); - cst_api_fill_to_wire_prepare_pay_onchain_response(apiObj.prepareRes, wireObj.prepare_res); + cst_api_fill_to_wire_prepare_pay_onchain_response(apiObj.prepareResponse, wireObj.prepare_response); } @protected void cst_api_fill_to_wire_payment(Payment apiObj, wire_cst_payment wireObj) { + wireObj.destination = cst_encode_opt_String(apiObj.destination); wireObj.tx_id = cst_encode_opt_String(apiObj.txId); - wireObj.swap_id = cst_encode_opt_String(apiObj.swapId); wireObj.timestamp = cst_encode_u_32(apiObj.timestamp); wireObj.amount_sat = cst_encode_u_64(apiObj.amountSat); wireObj.fees_sat = cst_encode_u_64(apiObj.feesSat); - wireObj.preimage = cst_encode_opt_String(apiObj.preimage); - wireObj.bolt11 = cst_encode_opt_String(apiObj.bolt11); - wireObj.description = cst_encode_String(apiObj.description); - wireObj.refund_tx_id = cst_encode_opt_String(apiObj.refundTxId); - wireObj.refund_tx_amount_sat = cst_encode_opt_box_autoadd_u_64(apiObj.refundTxAmountSat); wireObj.payment_type = cst_encode_payment_type(apiObj.paymentType); wireObj.status = cst_encode_payment_state(apiObj.status); + wireObj.details = cst_encode_opt_box_autoadd_payment_details(apiObj.details); + } + + @protected + void cst_api_fill_to_wire_payment_details(PaymentDetails apiObj, wire_cst_payment_details wireObj) { + if (apiObj is PaymentDetails_Lightning) { + var pre_swap_id = cst_encode_String(apiObj.swapId); + var pre_description = cst_encode_String(apiObj.description); + var pre_preimage = cst_encode_opt_String(apiObj.preimage); + var pre_bolt11 = cst_encode_opt_String(apiObj.bolt11); + var pre_refund_tx_id = cst_encode_opt_String(apiObj.refundTxId); + var pre_refund_tx_amount_sat = cst_encode_opt_box_autoadd_u_64(apiObj.refundTxAmountSat); + wireObj.tag = 0; + wireObj.kind.Lightning.swap_id = pre_swap_id; + wireObj.kind.Lightning.description = pre_description; + wireObj.kind.Lightning.preimage = pre_preimage; + wireObj.kind.Lightning.bolt11 = pre_bolt11; + wireObj.kind.Lightning.refund_tx_id = pre_refund_tx_id; + wireObj.kind.Lightning.refund_tx_amount_sat = pre_refund_tx_amount_sat; + return; + } + if (apiObj is PaymentDetails_Liquid) { + var pre_destination = cst_encode_String(apiObj.destination); + var pre_description = cst_encode_String(apiObj.description); + wireObj.tag = 1; + wireObj.kind.Liquid.destination = pre_destination; + wireObj.kind.Liquid.description = pre_description; + return; + } + if (apiObj is PaymentDetails_Bitcoin) { + var pre_swap_id = cst_encode_String(apiObj.swapId); + var pre_description = cst_encode_String(apiObj.description); + var pre_refund_tx_id = cst_encode_opt_String(apiObj.refundTxId); + var pre_refund_tx_amount_sat = cst_encode_opt_box_autoadd_u_64(apiObj.refundTxAmountSat); + wireObj.tag = 2; + wireObj.kind.Bitcoin.swap_id = pre_swap_id; + wireObj.kind.Bitcoin.description = pre_description; + wireObj.kind.Bitcoin.refund_tx_id = pre_refund_tx_id; + wireObj.kind.Bitcoin.refund_tx_amount_sat = pre_refund_tx_amount_sat; + return; + } } @protected @@ -2253,75 +2282,87 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl { wireObj.tag = 3; return; } - if (apiObj is PaymentError_Generic) { + if (apiObj is PaymentError_AmountMissing) { var pre_err = cst_encode_String(apiObj.err); wireObj.tag = 4; + wireObj.kind.AmountMissing.err = pre_err; + return; + } + if (apiObj is PaymentError_InvalidNetwork) { + var pre_err = cst_encode_String(apiObj.err); + wireObj.tag = 5; + wireObj.kind.InvalidNetwork.err = pre_err; + return; + } + if (apiObj is PaymentError_Generic) { + var pre_err = cst_encode_String(apiObj.err); + wireObj.tag = 6; wireObj.kind.Generic.err = pre_err; return; } if (apiObj is PaymentError_InvalidOrExpiredFees) { - wireObj.tag = 5; + wireObj.tag = 7; return; } if (apiObj is PaymentError_InsufficientFunds) { - wireObj.tag = 6; + wireObj.tag = 8; return; } if (apiObj is PaymentError_InvalidInvoice) { var pre_err = cst_encode_String(apiObj.err); - wireObj.tag = 7; + wireObj.tag = 9; wireObj.kind.InvalidInvoice.err = pre_err; return; } if (apiObj is PaymentError_InvalidPreimage) { - wireObj.tag = 8; + wireObj.tag = 10; return; } if (apiObj is PaymentError_LwkError) { var pre_err = cst_encode_String(apiObj.err); - wireObj.tag = 9; + wireObj.tag = 11; wireObj.kind.LwkError.err = pre_err; return; } if (apiObj is PaymentError_PairsNotFound) { - wireObj.tag = 10; + wireObj.tag = 12; return; } if (apiObj is PaymentError_PaymentTimeout) { - wireObj.tag = 11; + wireObj.tag = 13; return; } if (apiObj is PaymentError_PersistError) { - wireObj.tag = 12; + wireObj.tag = 14; return; } if (apiObj is PaymentError_ReceiveError) { var pre_err = cst_encode_String(apiObj.err); - wireObj.tag = 13; + wireObj.tag = 15; wireObj.kind.ReceiveError.err = pre_err; return; } if (apiObj is PaymentError_Refunded) { var pre_err = cst_encode_String(apiObj.err); var pre_refund_tx_id = cst_encode_String(apiObj.refundTxId); - wireObj.tag = 14; + wireObj.tag = 16; wireObj.kind.Refunded.err = pre_err; wireObj.kind.Refunded.refund_tx_id = pre_refund_tx_id; return; } if (apiObj is PaymentError_SelfTransferNotSupported) { - wireObj.tag = 15; + wireObj.tag = 17; return; } if (apiObj is PaymentError_SendError) { var pre_err = cst_encode_String(apiObj.err); - wireObj.tag = 16; + wireObj.tag = 18; wireObj.kind.SendError.err = pre_err; return; } if (apiObj is PaymentError_SignerError) { var pre_err = cst_encode_String(apiObj.err); - wireObj.tag = 17; + wireObj.tag = 19; wireObj.kind.SignerError.err = pre_err; return; } @@ -2358,28 +2399,17 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl { } @protected - void cst_api_fill_to_wire_prepare_receive_onchain_request( - PrepareReceiveOnchainRequest apiObj, wire_cst_prepare_receive_onchain_request wireObj) { - wireObj.payer_amount_sat = cst_encode_u_64(apiObj.payerAmountSat); + void cst_api_fill_to_wire_prepare_receive_request( + PrepareReceiveRequest apiObj, wire_cst_prepare_receive_request wireObj) { + wireObj.payer_amount_sat = cst_encode_opt_box_autoadd_u_64(apiObj.payerAmountSat); + wireObj.payment_method = cst_encode_payment_method(apiObj.paymentMethod); } @protected - void cst_api_fill_to_wire_prepare_receive_onchain_response( - PrepareReceiveOnchainResponse apiObj, wire_cst_prepare_receive_onchain_response wireObj) { - wireObj.payer_amount_sat = cst_encode_u_64(apiObj.payerAmountSat); - wireObj.fees_sat = cst_encode_u_64(apiObj.feesSat); - } - - @protected - void cst_api_fill_to_wire_prepare_receive_payment_request( - PrepareReceivePaymentRequest apiObj, wire_cst_prepare_receive_payment_request wireObj) { - wireObj.payer_amount_sat = cst_encode_u_64(apiObj.payerAmountSat); - } - - @protected - void cst_api_fill_to_wire_prepare_receive_payment_response( - PrepareReceivePaymentResponse apiObj, wire_cst_prepare_receive_payment_response wireObj) { - wireObj.payer_amount_sat = cst_encode_u_64(apiObj.payerAmountSat); + void cst_api_fill_to_wire_prepare_receive_response( + PrepareReceiveResponse apiObj, wire_cst_prepare_receive_response wireObj) { + wireObj.payment_method = cst_encode_payment_method(apiObj.paymentMethod); + wireObj.payer_amount_sat = cst_encode_opt_box_autoadd_u_64(apiObj.payerAmountSat); wireObj.fees_sat = cst_encode_u_64(apiObj.feesSat); } @@ -2402,13 +2432,14 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl { @protected void cst_api_fill_to_wire_prepare_send_request( PrepareSendRequest apiObj, wire_cst_prepare_send_request wireObj) { - wireObj.invoice = cst_encode_String(apiObj.invoice); + wireObj.destination = cst_encode_String(apiObj.destination); + wireObj.amount_sat = cst_encode_opt_box_autoadd_u_64(apiObj.amountSat); } @protected void cst_api_fill_to_wire_prepare_send_response( PrepareSendResponse apiObj, wire_cst_prepare_send_response wireObj) { - wireObj.invoice = cst_encode_String(apiObj.invoice); + cst_api_fill_to_wire_send_destination(apiObj.destination, wireObj.destination); wireObj.fees_sat = cst_encode_u_64(apiObj.feesSat); } @@ -2418,25 +2449,17 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl { wireObj.value = cst_encode_f_64(apiObj.value); } - @protected - void cst_api_fill_to_wire_receive_onchain_response( - ReceiveOnchainResponse apiObj, wire_cst_receive_onchain_response wireObj) { - wireObj.address = cst_encode_String(apiObj.address); - wireObj.bip21 = cst_encode_String(apiObj.bip21); - } - @protected void cst_api_fill_to_wire_receive_payment_request( ReceivePaymentRequest apiObj, wire_cst_receive_payment_request wireObj) { wireObj.description = cst_encode_opt_String(apiObj.description); - cst_api_fill_to_wire_prepare_receive_payment_response(apiObj.prepareRes, wireObj.prepare_res); + cst_api_fill_to_wire_prepare_receive_response(apiObj.prepareResponse, wireObj.prepare_response); } @protected void cst_api_fill_to_wire_receive_payment_response( ReceivePaymentResponse apiObj, wire_cst_receive_payment_response wireObj) { - wireObj.id = cst_encode_String(apiObj.id); - wireObj.invoice = cst_encode_String(apiObj.invoice); + wireObj.destination = cst_encode_String(apiObj.destination); } @protected @@ -2556,6 +2579,28 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl { } } + @protected + void cst_api_fill_to_wire_send_destination(SendDestination apiObj, wire_cst_send_destination wireObj) { + if (apiObj is SendDestination_LiquidAddress) { + var pre_address_data = cst_encode_box_autoadd_liquid_address_data(apiObj.addressData); + wireObj.tag = 0; + wireObj.kind.LiquidAddress.address_data = pre_address_data; + return; + } + if (apiObj is SendDestination_Bolt11) { + var pre_invoice = cst_encode_box_autoadd_ln_invoice(apiObj.invoice); + wireObj.tag = 1; + wireObj.kind.Bolt11.invoice = pre_invoice; + return; + } + } + + @protected + void cst_api_fill_to_wire_send_payment_request( + SendPaymentRequest apiObj, wire_cst_send_payment_request wireObj) { + cst_api_fill_to_wire_prepare_send_response(apiObj.prepareResponse, wireObj.prepare_response); + } + @protected void cst_api_fill_to_wire_send_payment_response( SendPaymentResponse apiObj, wire_cst_send_payment_response wireObj) { @@ -2631,6 +2676,9 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl { @protected int cst_encode_network(Network raw); + @protected + int cst_encode_payment_method(PaymentMethod raw); + @protected int cst_encode_payment_state(PaymentState raw); @@ -2769,6 +2817,9 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl { @protected void sse_encode_box_autoadd_payment(Payment self, SseSerializer serializer); + @protected + void sse_encode_box_autoadd_payment_details(PaymentDetails self, SseSerializer serializer); + @protected void sse_encode_box_autoadd_prepare_buy_bitcoin_request( PrepareBuyBitcoinRequest self, SseSerializer serializer); @@ -2778,16 +2829,7 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl { PreparePayOnchainRequest self, SseSerializer serializer); @protected - void sse_encode_box_autoadd_prepare_receive_onchain_request( - PrepareReceiveOnchainRequest self, SseSerializer serializer); - - @protected - void sse_encode_box_autoadd_prepare_receive_onchain_response( - PrepareReceiveOnchainResponse self, SseSerializer serializer); - - @protected - void sse_encode_box_autoadd_prepare_receive_payment_request( - PrepareReceivePaymentRequest self, SseSerializer serializer); + void sse_encode_box_autoadd_prepare_receive_request(PrepareReceiveRequest self, SseSerializer serializer); @protected void sse_encode_box_autoadd_prepare_refund_request(PrepareRefundRequest self, SseSerializer serializer); @@ -2795,9 +2837,6 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl { @protected void sse_encode_box_autoadd_prepare_send_request(PrepareSendRequest self, SseSerializer serializer); - @protected - void sse_encode_box_autoadd_prepare_send_response(PrepareSendResponse self, SseSerializer serializer); - @protected void sse_encode_box_autoadd_receive_payment_request(ReceivePaymentRequest self, SseSerializer serializer); @@ -2810,6 +2849,9 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl { @protected void sse_encode_box_autoadd_sdk_event(SdkEvent self, SseSerializer serializer); + @protected + void sse_encode_box_autoadd_send_payment_request(SendPaymentRequest self, SseSerializer serializer); + @protected void sse_encode_box_autoadd_success_action_processed(SuccessActionProcessed self, SseSerializer serializer); @@ -2980,6 +3022,9 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl { @protected void sse_encode_opt_box_autoadd_i_64(PlatformInt64? self, SseSerializer serializer); + @protected + void sse_encode_opt_box_autoadd_payment_details(PaymentDetails? self, SseSerializer serializer); + @protected void sse_encode_opt_box_autoadd_success_action_processed( SuccessActionProcessed? self, SseSerializer serializer); @@ -3002,9 +3047,15 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl { @protected void sse_encode_payment(Payment self, SseSerializer serializer); + @protected + void sse_encode_payment_details(PaymentDetails self, SseSerializer serializer); + @protected void sse_encode_payment_error(PaymentError self, SseSerializer serializer); + @protected + void sse_encode_payment_method(PaymentMethod self, SseSerializer serializer); + @protected void sse_encode_payment_state(PaymentState self, SseSerializer serializer); @@ -3024,20 +3075,10 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl { void sse_encode_prepare_pay_onchain_response(PreparePayOnchainResponse self, SseSerializer serializer); @protected - void sse_encode_prepare_receive_onchain_request( - PrepareReceiveOnchainRequest self, SseSerializer serializer); + void sse_encode_prepare_receive_request(PrepareReceiveRequest self, SseSerializer serializer); @protected - void sse_encode_prepare_receive_onchain_response( - PrepareReceiveOnchainResponse self, SseSerializer serializer); - - @protected - void sse_encode_prepare_receive_payment_request( - PrepareReceivePaymentRequest self, SseSerializer serializer); - - @protected - void sse_encode_prepare_receive_payment_response( - PrepareReceivePaymentResponse self, SseSerializer serializer); + void sse_encode_prepare_receive_response(PrepareReceiveResponse self, SseSerializer serializer); @protected void sse_encode_prepare_refund_request(PrepareRefundRequest self, SseSerializer serializer); @@ -3054,9 +3095,6 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl { @protected void sse_encode_rate(Rate self, SseSerializer serializer); - @protected - void sse_encode_receive_onchain_response(ReceiveOnchainResponse self, SseSerializer serializer); - @protected void sse_encode_receive_payment_request(ReceivePaymentRequest self, SseSerializer serializer); @@ -3090,6 +3128,12 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl { @protected void sse_encode_sdk_event(SdkEvent self, SseSerializer serializer); + @protected + void sse_encode_send_destination(SendDestination self, SseSerializer serializer); + + @protected + void sse_encode_send_payment_request(SendPaymentRequest self, SseSerializer serializer); + @protected void sse_encode_send_payment_response(SendPaymentResponse self, SseSerializer serializer); @@ -3482,31 +3526,10 @@ class RustLibWire implements BaseWire { _wire__crate__bindings__BindingLiquidSdk_prepare_pay_onchainPtr .asFunction)>(); - void wire__crate__bindings__BindingLiquidSdk_prepare_receive_onchain( - int port_, - int that, - ffi.Pointer req, - ) { - return _wire__crate__bindings__BindingLiquidSdk_prepare_receive_onchain( - port_, - that, - req, - ); - } - - late final _wire__crate__bindings__BindingLiquidSdk_prepare_receive_onchainPtr = _lookup< - ffi.NativeFunction< - ffi.Void Function( - ffi.Int64, ffi.UintPtr, ffi.Pointer)>>( - 'frbgen_breez_liquid_wire__crate__bindings__BindingLiquidSdk_prepare_receive_onchain'); - late final _wire__crate__bindings__BindingLiquidSdk_prepare_receive_onchain = - _wire__crate__bindings__BindingLiquidSdk_prepare_receive_onchainPtr - .asFunction)>(); - void wire__crate__bindings__BindingLiquidSdk_prepare_receive_payment( int port_, int that, - ffi.Pointer req, + ffi.Pointer req, ) { return _wire__crate__bindings__BindingLiquidSdk_prepare_receive_payment( port_, @@ -3517,12 +3540,11 @@ class RustLibWire implements BaseWire { late final _wire__crate__bindings__BindingLiquidSdk_prepare_receive_paymentPtr = _lookup< ffi.NativeFunction< - ffi.Void Function( - ffi.Int64, ffi.UintPtr, ffi.Pointer)>>( + ffi.Void Function(ffi.Int64, ffi.UintPtr, ffi.Pointer)>>( 'frbgen_breez_liquid_wire__crate__bindings__BindingLiquidSdk_prepare_receive_payment'); late final _wire__crate__bindings__BindingLiquidSdk_prepare_receive_payment = _wire__crate__bindings__BindingLiquidSdk_prepare_receive_paymentPtr - .asFunction)>(); + .asFunction)>(); void wire__crate__bindings__BindingLiquidSdk_prepare_refund( int port_, @@ -3564,27 +3586,6 @@ class RustLibWire implements BaseWire { _wire__crate__bindings__BindingLiquidSdk_prepare_send_paymentPtr .asFunction)>(); - void wire__crate__bindings__BindingLiquidSdk_receive_onchain( - int port_, - int that, - ffi.Pointer req, - ) { - return _wire__crate__bindings__BindingLiquidSdk_receive_onchain( - port_, - that, - req, - ); - } - - late final _wire__crate__bindings__BindingLiquidSdk_receive_onchainPtr = _lookup< - ffi.NativeFunction< - ffi.Void Function( - ffi.Int64, ffi.UintPtr, ffi.Pointer)>>( - 'frbgen_breez_liquid_wire__crate__bindings__BindingLiquidSdk_receive_onchain'); - late final _wire__crate__bindings__BindingLiquidSdk_receive_onchain = - _wire__crate__bindings__BindingLiquidSdk_receive_onchainPtr - .asFunction)>(); - void wire__crate__bindings__BindingLiquidSdk_receive_payment( int port_, int that, @@ -3678,7 +3679,7 @@ class RustLibWire implements BaseWire { void wire__crate__bindings__BindingLiquidSdk_send_payment( int port_, int that, - ffi.Pointer req, + ffi.Pointer req, ) { return _wire__crate__bindings__BindingLiquidSdk_send_payment( port_, @@ -3689,11 +3690,11 @@ class RustLibWire implements BaseWire { late final _wire__crate__bindings__BindingLiquidSdk_send_paymentPtr = _lookup< ffi.NativeFunction< - ffi.Void Function(ffi.Int64, ffi.UintPtr, ffi.Pointer)>>( + ffi.Void Function(ffi.Int64, ffi.UintPtr, ffi.Pointer)>>( 'frbgen_breez_liquid_wire__crate__bindings__BindingLiquidSdk_send_payment'); late final _wire__crate__bindings__BindingLiquidSdk_send_payment = _wire__crate__bindings__BindingLiquidSdk_send_paymentPtr - .asFunction)>(); + .asFunction)>(); void wire__crate__bindings__BindingLiquidSdk_sync( int port_, @@ -4095,6 +4096,16 @@ class RustLibWire implements BaseWire { late final _cst_new_box_autoadd_payment = _cst_new_box_autoadd_paymentPtr.asFunction Function()>(); + ffi.Pointer cst_new_box_autoadd_payment_details() { + return _cst_new_box_autoadd_payment_details(); + } + + late final _cst_new_box_autoadd_payment_detailsPtr = + _lookup Function()>>( + 'frbgen_breez_liquid_cst_new_box_autoadd_payment_details'); + late final _cst_new_box_autoadd_payment_details = + _cst_new_box_autoadd_payment_detailsPtr.asFunction Function()>(); + ffi.Pointer cst_new_box_autoadd_prepare_buy_bitcoin_request() { return _cst_new_box_autoadd_prepare_buy_bitcoin_request(); } @@ -4117,41 +4128,15 @@ class RustLibWire implements BaseWire { _cst_new_box_autoadd_prepare_pay_onchain_requestPtr .asFunction Function()>(); - ffi.Pointer - cst_new_box_autoadd_prepare_receive_onchain_request() { - return _cst_new_box_autoadd_prepare_receive_onchain_request(); + ffi.Pointer cst_new_box_autoadd_prepare_receive_request() { + return _cst_new_box_autoadd_prepare_receive_request(); } - late final _cst_new_box_autoadd_prepare_receive_onchain_requestPtr = - _lookup Function()>>( - 'frbgen_breez_liquid_cst_new_box_autoadd_prepare_receive_onchain_request'); - late final _cst_new_box_autoadd_prepare_receive_onchain_request = - _cst_new_box_autoadd_prepare_receive_onchain_requestPtr - .asFunction Function()>(); - - ffi.Pointer - cst_new_box_autoadd_prepare_receive_onchain_response() { - return _cst_new_box_autoadd_prepare_receive_onchain_response(); - } - - late final _cst_new_box_autoadd_prepare_receive_onchain_responsePtr = - _lookup Function()>>( - 'frbgen_breez_liquid_cst_new_box_autoadd_prepare_receive_onchain_response'); - late final _cst_new_box_autoadd_prepare_receive_onchain_response = - _cst_new_box_autoadd_prepare_receive_onchain_responsePtr - .asFunction Function()>(); - - ffi.Pointer - cst_new_box_autoadd_prepare_receive_payment_request() { - return _cst_new_box_autoadd_prepare_receive_payment_request(); - } - - late final _cst_new_box_autoadd_prepare_receive_payment_requestPtr = - _lookup Function()>>( - 'frbgen_breez_liquid_cst_new_box_autoadd_prepare_receive_payment_request'); - late final _cst_new_box_autoadd_prepare_receive_payment_request = - _cst_new_box_autoadd_prepare_receive_payment_requestPtr - .asFunction Function()>(); + late final _cst_new_box_autoadd_prepare_receive_requestPtr = + _lookup Function()>>( + 'frbgen_breez_liquid_cst_new_box_autoadd_prepare_receive_request'); + late final _cst_new_box_autoadd_prepare_receive_request = _cst_new_box_autoadd_prepare_receive_requestPtr + .asFunction Function()>(); ffi.Pointer cst_new_box_autoadd_prepare_refund_request() { return _cst_new_box_autoadd_prepare_refund_request(); @@ -4173,16 +4158,6 @@ class RustLibWire implements BaseWire { late final _cst_new_box_autoadd_prepare_send_request = _cst_new_box_autoadd_prepare_send_requestPtr .asFunction Function()>(); - ffi.Pointer cst_new_box_autoadd_prepare_send_response() { - return _cst_new_box_autoadd_prepare_send_response(); - } - - late final _cst_new_box_autoadd_prepare_send_responsePtr = - _lookup Function()>>( - 'frbgen_breez_liquid_cst_new_box_autoadd_prepare_send_response'); - late final _cst_new_box_autoadd_prepare_send_response = _cst_new_box_autoadd_prepare_send_responsePtr - .asFunction Function()>(); - ffi.Pointer cst_new_box_autoadd_receive_payment_request() { return _cst_new_box_autoadd_receive_payment_request(); } @@ -4223,6 +4198,16 @@ class RustLibWire implements BaseWire { late final _cst_new_box_autoadd_sdk_event = _cst_new_box_autoadd_sdk_eventPtr.asFunction Function()>(); + ffi.Pointer cst_new_box_autoadd_send_payment_request() { + return _cst_new_box_autoadd_send_payment_request(); + } + + late final _cst_new_box_autoadd_send_payment_requestPtr = + _lookup Function()>>( + 'frbgen_breez_liquid_cst_new_box_autoadd_send_payment_request'); + late final _cst_new_box_autoadd_send_payment_request = _cst_new_box_autoadd_send_payment_requestPtr + .asFunction Function()>(); + ffi.Pointer cst_new_box_autoadd_success_action_processed() { return _cst_new_box_autoadd_success_action_processed(); } @@ -4461,7 +4446,7 @@ final class wire_cst_prepare_buy_bitcoin_response extends ffi.Struct { } final class wire_cst_buy_bitcoin_request extends ffi.Struct { - external wire_cst_prepare_buy_bitcoin_response prepare_res; + external wire_cst_prepare_buy_bitcoin_response prepare_response; external ffi.Pointer redirect_url; } @@ -4569,7 +4554,7 @@ final class wire_cst_prepare_pay_onchain_response extends ffi.Struct { final class wire_cst_pay_onchain_request extends ffi.Struct { external ffi.Pointer address; - external wire_cst_prepare_pay_onchain_response prepare_res; + external wire_cst_prepare_pay_onchain_response prepare_response; } final class wire_cst_prepare_buy_bitcoin_request extends ffi.Struct { @@ -4587,14 +4572,11 @@ final class wire_cst_prepare_pay_onchain_request extends ffi.Struct { external ffi.Pointer sat_per_vbyte; } -final class wire_cst_prepare_receive_onchain_request extends ffi.Struct { - @ffi.Uint64() - external int payer_amount_sat; -} +final class wire_cst_prepare_receive_request extends ffi.Struct { + external ffi.Pointer payer_amount_sat; -final class wire_cst_prepare_receive_payment_request extends ffi.Struct { - @ffi.Uint64() - external int payer_amount_sat; + @ffi.Int32() + external int payment_method; } final class wire_cst_prepare_refund_request extends ffi.Struct { @@ -4607,20 +4589,16 @@ final class wire_cst_prepare_refund_request extends ffi.Struct { } final class wire_cst_prepare_send_request extends ffi.Struct { - external ffi.Pointer invoice; + external ffi.Pointer destination; + + external ffi.Pointer amount_sat; } -final class wire_cst_prepare_receive_onchain_response extends ffi.Struct { - @ffi.Uint64() - external int payer_amount_sat; +final class wire_cst_prepare_receive_response extends ffi.Struct { + @ffi.Int32() + external int payment_method; - @ffi.Uint64() - external int fees_sat; -} - -final class wire_cst_prepare_receive_payment_response extends ffi.Struct { - @ffi.Uint64() - external int payer_amount_sat; + external ffi.Pointer payer_amount_sat; @ffi.Uint64() external int fees_sat; @@ -4629,7 +4607,7 @@ final class wire_cst_prepare_receive_payment_response extends ffi.Struct { final class wire_cst_receive_payment_request extends ffi.Struct { external ffi.Pointer description; - external wire_cst_prepare_receive_payment_response prepare_res; + external wire_cst_prepare_receive_response prepare_response; } final class wire_cst_refund_request extends ffi.Struct { @@ -4645,22 +4623,175 @@ final class wire_cst_restore_request extends ffi.Struct { external ffi.Pointer backup_path; } +final class wire_cst_liquid_address_data extends ffi.Struct { + external ffi.Pointer address; + + @ffi.Int32() + external int network; + + external ffi.Pointer asset_id; + + external ffi.Pointer amount_sat; + + external ffi.Pointer label; + + external ffi.Pointer message; +} + +final class wire_cst_SendDestination_LiquidAddress extends ffi.Struct { + external ffi.Pointer address_data; +} + +final class wire_cst_route_hint_hop extends ffi.Struct { + external ffi.Pointer src_node_id; + + @ffi.Uint64() + external int short_channel_id; + + @ffi.Uint32() + external int fees_base_msat; + + @ffi.Uint32() + external int fees_proportional_millionths; + + @ffi.Uint64() + external int cltv_expiry_delta; + + external ffi.Pointer htlc_minimum_msat; + + external ffi.Pointer htlc_maximum_msat; +} + +final class wire_cst_list_route_hint_hop extends ffi.Struct { + external ffi.Pointer ptr; + + @ffi.Int32() + external int len; +} + +final class wire_cst_route_hint extends ffi.Struct { + external ffi.Pointer hops; +} + +final class wire_cst_list_route_hint extends ffi.Struct { + external ffi.Pointer ptr; + + @ffi.Int32() + external int len; +} + +final class wire_cst_ln_invoice extends ffi.Struct { + external ffi.Pointer bolt11; + + @ffi.Int32() + external int network; + + external ffi.Pointer payee_pubkey; + + external ffi.Pointer payment_hash; + + external ffi.Pointer description; + + external ffi.Pointer description_hash; + + external ffi.Pointer amount_msat; + + @ffi.Uint64() + external int timestamp; + + @ffi.Uint64() + external int expiry; + + external ffi.Pointer routing_hints; + + external ffi.Pointer payment_secret; + + @ffi.Uint64() + external int min_final_cltv_expiry_delta; +} + +final class wire_cst_SendDestination_Bolt11 extends ffi.Struct { + external ffi.Pointer invoice; +} + +final class SendDestinationKind extends ffi.Union { + external wire_cst_SendDestination_LiquidAddress LiquidAddress; + + external wire_cst_SendDestination_Bolt11 Bolt11; +} + +final class wire_cst_send_destination extends ffi.Struct { + @ffi.Int32() + external int tag; + + external SendDestinationKind kind; +} + final class wire_cst_prepare_send_response extends ffi.Struct { - external ffi.Pointer invoice; + external wire_cst_send_destination destination; @ffi.Uint64() external int fees_sat; } +final class wire_cst_send_payment_request extends ffi.Struct { + external wire_cst_prepare_send_response prepare_response; +} + final class wire_cst_binding_event_listener extends ffi.Struct { external ffi.Pointer stream; } -final class wire_cst_payment extends ffi.Struct { - external ffi.Pointer tx_id; - +final class wire_cst_PaymentDetails_Lightning extends ffi.Struct { external ffi.Pointer swap_id; + external ffi.Pointer description; + + external ffi.Pointer preimage; + + external ffi.Pointer bolt11; + + external ffi.Pointer refund_tx_id; + + external ffi.Pointer refund_tx_amount_sat; +} + +final class wire_cst_PaymentDetails_Liquid extends ffi.Struct { + external ffi.Pointer destination; + + external ffi.Pointer description; +} + +final class wire_cst_PaymentDetails_Bitcoin extends ffi.Struct { + external ffi.Pointer swap_id; + + external ffi.Pointer description; + + external ffi.Pointer refund_tx_id; + + external ffi.Pointer refund_tx_amount_sat; +} + +final class PaymentDetailsKind extends ffi.Union { + external wire_cst_PaymentDetails_Lightning Lightning; + + external wire_cst_PaymentDetails_Liquid Liquid; + + external wire_cst_PaymentDetails_Bitcoin Bitcoin; +} + +final class wire_cst_payment_details extends ffi.Struct { + @ffi.Int32() + external int tag; + + external PaymentDetailsKind kind; +} + +final class wire_cst_payment extends ffi.Struct { + external ffi.Pointer destination; + + external ffi.Pointer tx_id; + @ffi.Uint32() external int timestamp; @@ -4670,21 +4801,13 @@ final class wire_cst_payment extends ffi.Struct { @ffi.Uint64() external int fees_sat; - external ffi.Pointer preimage; - - external ffi.Pointer bolt11; - - external ffi.Pointer description; - - external ffi.Pointer refund_tx_id; - - external ffi.Pointer refund_tx_amount_sat; - @ffi.Int32() external int payment_type; @ffi.Int32() external int status; + + external ffi.Pointer details; } final class wire_cst_SdkEvent_PaymentFailed extends ffi.Struct { @@ -4799,89 +4922,6 @@ final class wire_cst_bitcoin_address_data extends ffi.Struct { external ffi.Pointer message; } -final class wire_cst_liquid_address_data extends ffi.Struct { - external ffi.Pointer address; - - @ffi.Int32() - external int network; - - external ffi.Pointer asset_id; - - external ffi.Pointer amount_sat; - - external ffi.Pointer label; - - external ffi.Pointer message; -} - -final class wire_cst_route_hint_hop extends ffi.Struct { - external ffi.Pointer src_node_id; - - @ffi.Uint64() - external int short_channel_id; - - @ffi.Uint32() - external int fees_base_msat; - - @ffi.Uint32() - external int fees_proportional_millionths; - - @ffi.Uint64() - external int cltv_expiry_delta; - - external ffi.Pointer htlc_minimum_msat; - - external ffi.Pointer htlc_maximum_msat; -} - -final class wire_cst_list_route_hint_hop extends ffi.Struct { - external ffi.Pointer ptr; - - @ffi.Int32() - external int len; -} - -final class wire_cst_route_hint extends ffi.Struct { - external ffi.Pointer hops; -} - -final class wire_cst_list_route_hint extends ffi.Struct { - external ffi.Pointer ptr; - - @ffi.Int32() - external int len; -} - -final class wire_cst_ln_invoice extends ffi.Struct { - external ffi.Pointer bolt11; - - @ffi.Int32() - external int network; - - external ffi.Pointer payee_pubkey; - - external ffi.Pointer payment_hash; - - external ffi.Pointer description; - - external ffi.Pointer description_hash; - - external ffi.Pointer amount_msat; - - @ffi.Uint64() - external int timestamp; - - @ffi.Uint64() - external int expiry; - - external ffi.Pointer routing_hints; - - external ffi.Pointer payment_secret; - - @ffi.Uint64() - external int min_final_cltv_expiry_delta; -} - final class wire_cst_ln_url_error_data extends ffi.Struct { external ffi.Pointer reason; } @@ -5369,6 +5409,14 @@ final class wire_cst_onchain_payment_limits_response extends ffi.Struct { external wire_cst_limits receive; } +final class wire_cst_PaymentError_AmountMissing extends ffi.Struct { + external ffi.Pointer err; +} + +final class wire_cst_PaymentError_InvalidNetwork extends ffi.Struct { + external ffi.Pointer err; +} + final class wire_cst_PaymentError_Generic extends ffi.Struct { external ffi.Pointer err; } @@ -5400,6 +5448,10 @@ final class wire_cst_PaymentError_SignerError extends ffi.Struct { } final class PaymentErrorKind extends ffi.Union { + external wire_cst_PaymentError_AmountMissing AmountMissing; + + external wire_cst_PaymentError_InvalidNetwork InvalidNetwork; + external wire_cst_PaymentError_Generic Generic; external wire_cst_PaymentError_InvalidInvoice InvalidInvoice; @@ -5432,16 +5484,8 @@ final class wire_cst_prepare_refund_response extends ffi.Struct { external ffi.Pointer refund_tx_id; } -final class wire_cst_receive_onchain_response extends ffi.Struct { - external ffi.Pointer address; - - external ffi.Pointer bip21; -} - final class wire_cst_receive_payment_response extends ffi.Struct { - external ffi.Pointer id; - - external ffi.Pointer invoice; + external ffi.Pointer destination; } final class wire_cst_recommended_fees extends ffi.Struct { diff --git a/packages/dart/lib/src/model.dart b/packages/dart/lib/src/model.dart index eed1fb4..a47a1db 100644 --- a/packages/dart/lib/src/model.dart +++ b/packages/dart/lib/src/model.dart @@ -38,7 +38,7 @@ enum BuyBitcoinProvider { /// An argument when calling [crate::sdk::LiquidSdk::buy_bitcoin]. class BuyBitcoinRequest { - final PrepareBuyBitcoinResponse prepareRes; + final PrepareBuyBitcoinResponse prepareResponse; /// The optional URL to redirect to after completing the buy. /// @@ -46,19 +46,19 @@ class BuyBitcoinRequest { final String? redirectUrl; const BuyBitcoinRequest({ - required this.prepareRes, + required this.prepareResponse, this.redirectUrl, }); @override - int get hashCode => prepareRes.hashCode ^ redirectUrl.hashCode; + int get hashCode => prepareResponse.hashCode ^ redirectUrl.hashCode; @override bool operator ==(Object other) => identical(this, other) || other is BuyBitcoinRequest && runtimeType == other.runtimeType && - prepareRes == other.prepareRes && + prepareResponse == other.prepareResponse && redirectUrl == other.redirectUrl; } @@ -359,15 +359,15 @@ class OnchainPaymentLimitsResponse { /// An argument when calling [crate::sdk::LiquidSdk::pay_onchain]. class PayOnchainRequest { final String address; - final PreparePayOnchainResponse prepareRes; + final PreparePayOnchainResponse prepareResponse; const PayOnchainRequest({ required this.address, - required this.prepareRes, + required this.prepareResponse, }); @override - int get hashCode => address.hashCode ^ prepareRes.hashCode; + int get hashCode => address.hashCode ^ prepareResponse.hashCode; @override bool operator ==(Object other) => @@ -375,18 +375,18 @@ class PayOnchainRequest { other is PayOnchainRequest && runtimeType == other.runtimeType && address == other.address && - prepareRes == other.prepareRes; + prepareResponse == other.prepareResponse; } /// Represents an SDK payment. /// /// By default, this is an onchain tx. It may represent a swap, if swap metadata is available. class Payment { + /// The destination associated with the payment, if it was created via our SDK. + /// Can be either a Liquid/Bitcoin address, a Liquid BIP21 URI or an invoice + final String? destination; final String? txId; - /// The swap ID, if any swap is associated with this payment - final String? swapId; - /// Composite timestamp that can be used for sorting or displaying the payment. /// /// If this payment has an associated swap, it is the swap creation time. Otherwise, the point @@ -414,23 +414,6 @@ class Payment { /// - for Receive payments, this is zero final BigInt feesSat; - /// In case of a Send swap, this is the preimage of the paid invoice (proof of payment). - final String? preimage; - - /// Represents the invoice associated with a payment - /// In the case of a Send payment, this is the invoice paid by the swapper - /// In the case of a Receive payment, this is the invoice paid by the user - final String? bolt11; - - /// Represents the invoice description - final String description; - - /// For a Send swap which was refunded, this is the refund tx id - final String? refundTxId; - - /// For a Send swap which was refunded, this is the refund amount - final BigInt? refundTxAmountSat; - /// If it is a `Send` or `Receive` payment final PaymentType paymentType; @@ -441,53 +424,103 @@ class Payment { /// If the tx has an associated swap, this is determined by the swap status (pending or complete). final PaymentState status; + /// The details of a payment, depending on its [destination](Payment::destination) and + /// [type](Payment::payment_type) + final PaymentDetails? details; + const Payment({ + this.destination, this.txId, - this.swapId, required this.timestamp, required this.amountSat, required this.feesSat, - this.preimage, - this.bolt11, - required this.description, - this.refundTxId, - this.refundTxAmountSat, required this.paymentType, required this.status, + this.details, }); @override int get hashCode => + destination.hashCode ^ txId.hashCode ^ - swapId.hashCode ^ timestamp.hashCode ^ amountSat.hashCode ^ feesSat.hashCode ^ - preimage.hashCode ^ - bolt11.hashCode ^ - description.hashCode ^ - refundTxId.hashCode ^ - refundTxAmountSat.hashCode ^ paymentType.hashCode ^ - status.hashCode; + status.hashCode ^ + details.hashCode; @override bool operator ==(Object other) => identical(this, other) || other is Payment && runtimeType == other.runtimeType && + destination == other.destination && txId == other.txId && - swapId == other.swapId && timestamp == other.timestamp && amountSat == other.amountSat && feesSat == other.feesSat && - preimage == other.preimage && - bolt11 == other.bolt11 && - description == other.description && - refundTxId == other.refundTxId && - refundTxAmountSat == other.refundTxAmountSat && paymentType == other.paymentType && - status == other.status; + status == other.status && + details == other.details; +} + +@freezed +sealed class PaymentDetails with _$PaymentDetails { + const PaymentDetails._(); + + /// Swapping to or from Lightning + const factory PaymentDetails.lightning({ + required String swapId, + + /// Represents the invoice description + required String description, + + /// In case of a Send swap, this is the preimage of the paid invoice (proof of payment). + String? preimage, + + /// Represents the invoice associated with a payment + /// In the case of a Send payment, this is the invoice paid by the swapper + /// In the case of a Receive payment, this is the invoice paid by the user + String? bolt11, + + /// For a Send swap which was refunded, this is the refund tx id + String? refundTxId, + + /// For a Send swap which was refunded, this is the refund amount + BigInt? refundTxAmountSat, + }) = PaymentDetails_Lightning; + + /// Direct onchain payment to a Liquid address + const factory PaymentDetails.liquid({ + /// Represents either a Liquid BIP21 URI or pure address + required String destination, + + /// Represents the BIP21 `message` field + required String description, + }) = PaymentDetails_Liquid; + + /// Swapping to or from the Bitcoin chain + const factory PaymentDetails.bitcoin({ + required String swapId, + + /// Represents the invoice description + required String description, + + /// For a Send swap which was refunded, this is the refund tx id + String? refundTxId, + + /// For a Send swap which was refunded, this is the refund amount + BigInt? refundTxAmountSat, + }) = PaymentDetails_Bitcoin; +} + +/// The send/receive methods supported by the SDK +enum PaymentMethod { + lightning, + bitcoinAddress, + liquidAddress, + ; } /// The payment state of an individual payment. @@ -658,84 +691,49 @@ class PreparePayOnchainResponse { totalFeesSat == other.totalFeesSat; } -/// An argument when calling [crate::sdk::LiquidSdk::prepare_receive_onchain]. -class PrepareReceiveOnchainRequest { - final BigInt payerAmountSat; +/// An argument when calling [crate::sdk::LiquidSdk::prepare_receive_payment]. +class PrepareReceiveRequest { + final BigInt? payerAmountSat; + final PaymentMethod paymentMethod; - const PrepareReceiveOnchainRequest({ - required this.payerAmountSat, + const PrepareReceiveRequest({ + this.payerAmountSat, + required this.paymentMethod, }); @override - int get hashCode => payerAmountSat.hashCode; + int get hashCode => payerAmountSat.hashCode ^ paymentMethod.hashCode; @override bool operator ==(Object other) => identical(this, other) || - other is PrepareReceiveOnchainRequest && - runtimeType == other.runtimeType && - payerAmountSat == other.payerAmountSat; -} - -/// Returned when calling [crate::sdk::LiquidSdk::prepare_receive_onchain]. -class PrepareReceiveOnchainResponse { - final BigInt payerAmountSat; - final BigInt feesSat; - - const PrepareReceiveOnchainResponse({ - required this.payerAmountSat, - required this.feesSat, - }); - - @override - int get hashCode => payerAmountSat.hashCode ^ feesSat.hashCode; - - @override - bool operator ==(Object other) => - identical(this, other) || - other is PrepareReceiveOnchainResponse && + other is PrepareReceiveRequest && runtimeType == other.runtimeType && payerAmountSat == other.payerAmountSat && - feesSat == other.feesSat; -} - -/// An argument when calling [crate::sdk::LiquidSdk::prepare_receive_payment]. -class PrepareReceivePaymentRequest { - final BigInt payerAmountSat; - - const PrepareReceivePaymentRequest({ - required this.payerAmountSat, - }); - - @override - int get hashCode => payerAmountSat.hashCode; - - @override - bool operator ==(Object other) => - identical(this, other) || - other is PrepareReceivePaymentRequest && - runtimeType == other.runtimeType && - payerAmountSat == other.payerAmountSat; + paymentMethod == other.paymentMethod; } /// Returned when calling [crate::sdk::LiquidSdk::prepare_receive_payment]. -class PrepareReceivePaymentResponse { - final BigInt payerAmountSat; +class PrepareReceiveResponse { + final PaymentMethod paymentMethod; + final BigInt? payerAmountSat; final BigInt feesSat; - const PrepareReceivePaymentResponse({ - required this.payerAmountSat, + const PrepareReceiveResponse({ + required this.paymentMethod, + this.payerAmountSat, required this.feesSat, }); @override - int get hashCode => payerAmountSat.hashCode ^ feesSat.hashCode; + int get hashCode => paymentMethod.hashCode ^ payerAmountSat.hashCode ^ feesSat.hashCode; @override bool operator ==(Object other) => identical(this, other) || - other is PrepareReceivePaymentResponse && + other is PrepareReceiveResponse && runtimeType == other.runtimeType && + paymentMethod == other.paymentMethod && payerAmountSat == other.payerAmountSat && feesSat == other.feesSat; } @@ -797,77 +795,65 @@ class PrepareRefundResponse { /// An argument when calling [crate::sdk::LiquidSdk::prepare_send_payment]. class PrepareSendRequest { - final String invoice; + /// The destination we intend to pay to. + /// Supports BIP21 URIs, BOLT11 invoices and Liquid addresses + final String destination; + + /// Should only be set when paying directly onchain or to a BIP21 URI + /// where no amount is specified + final BigInt? amountSat; const PrepareSendRequest({ - required this.invoice, + required this.destination, + this.amountSat, }); @override - int get hashCode => invoice.hashCode; + int get hashCode => destination.hashCode ^ amountSat.hashCode; @override bool operator ==(Object other) => identical(this, other) || - other is PrepareSendRequest && runtimeType == other.runtimeType && invoice == other.invoice; + other is PrepareSendRequest && + runtimeType == other.runtimeType && + destination == other.destination && + amountSat == other.amountSat; } /// Returned when calling [crate::sdk::LiquidSdk::prepare_send_payment]. class PrepareSendResponse { - final String invoice; + final SendDestination destination; final BigInt feesSat; const PrepareSendResponse({ - required this.invoice, + required this.destination, required this.feesSat, }); @override - int get hashCode => invoice.hashCode ^ feesSat.hashCode; + int get hashCode => destination.hashCode ^ feesSat.hashCode; @override bool operator ==(Object other) => identical(this, other) || other is PrepareSendResponse && runtimeType == other.runtimeType && - invoice == other.invoice && + destination == other.destination && feesSat == other.feesSat; } -/// Returned when calling [crate::sdk::LiquidSdk::receive_onchain]. -class ReceiveOnchainResponse { - final String address; - final String bip21; - - const ReceiveOnchainResponse({ - required this.address, - required this.bip21, - }); - - @override - int get hashCode => address.hashCode ^ bip21.hashCode; - - @override - bool operator ==(Object other) => - identical(this, other) || - other is ReceiveOnchainResponse && - runtimeType == other.runtimeType && - address == other.address && - bip21 == other.bip21; -} - /// An argument when calling [crate::sdk::LiquidSdk::receive_payment]. class ReceivePaymentRequest { final String? description; - final PrepareReceivePaymentResponse prepareRes; + final PrepareReceiveResponse prepareResponse; const ReceivePaymentRequest({ this.description, - required this.prepareRes, + required this.prepareResponse, }); @override - int get hashCode => description.hashCode ^ prepareRes.hashCode; + int get hashCode => description.hashCode ^ prepareResponse.hashCode; @override bool operator ==(Object other) => @@ -875,29 +861,26 @@ class ReceivePaymentRequest { other is ReceivePaymentRequest && runtimeType == other.runtimeType && description == other.description && - prepareRes == other.prepareRes; + prepareResponse == other.prepareResponse; } /// Returned when calling [crate::sdk::LiquidSdk::receive_payment]. class ReceivePaymentResponse { - final String id; - final String invoice; + /// Either a BIP21 URI (Liquid or Bitcoin), a Liquid address + /// or an invoice, depending on the [PrepareReceivePaymentResponse] parameters + final String destination; const ReceivePaymentResponse({ - required this.id, - required this.invoice, + required this.destination, }); @override - int get hashCode => id.hashCode ^ invoice.hashCode; + int get hashCode => destination.hashCode; @override bool operator ==(Object other) => identical(this, other) || - other is ReceivePaymentResponse && - runtimeType == other.runtimeType && - id == other.id && - invoice == other.invoice; + other is ReceivePaymentResponse && runtimeType == other.runtimeType && destination == other.destination; } /// Returned when calling [crate::sdk::LiquidSdk::recommended_fees]. @@ -1050,6 +1033,37 @@ sealed class SdkEvent with _$SdkEvent { const factory SdkEvent.synced() = SdkEvent_Synced; } +@freezed +sealed class SendDestination with _$SendDestination { + const SendDestination._(); + + const factory SendDestination.liquidAddress({ + required LiquidAddressData addressData, + }) = SendDestination_LiquidAddress; + const factory SendDestination.bolt11({ + required LNInvoice invoice, + }) = SendDestination_Bolt11; +} + +/// An argument when calling [crate::sdk::LiquidSdk::send_payment]. +class SendPaymentRequest { + final PrepareSendResponse prepareResponse; + + const SendPaymentRequest({ + required this.prepareResponse, + }); + + @override + int get hashCode => prepareResponse.hashCode; + + @override + bool operator ==(Object other) => + identical(this, other) || + other is SendPaymentRequest && + runtimeType == other.runtimeType && + prepareResponse == other.prepareResponse; +} + /// Returned when calling [crate::sdk::LiquidSdk::send_payment]. class SendPaymentResponse { final Payment payment; diff --git a/packages/dart/lib/src/model.freezed.dart b/packages/dart/lib/src/model.freezed.dart index d5d856e..03ba4d2 100644 --- a/packages/dart/lib/src/model.freezed.dart +++ b/packages/dart/lib/src/model.freezed.dart @@ -283,6 +283,449 @@ abstract class LnUrlPayResult_PayError extends LnUrlPayResult { throw _privateConstructorUsedError; } +/// @nodoc +mixin _$PaymentDetails { + /// Represents the invoice description + String get description => throw _privateConstructorUsedError; + + /// Create a copy of PaymentDetails + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + $PaymentDetailsCopyWith get copyWith => throw _privateConstructorUsedError; +} + +/// @nodoc +abstract class $PaymentDetailsCopyWith<$Res> { + factory $PaymentDetailsCopyWith(PaymentDetails value, $Res Function(PaymentDetails) then) = + _$PaymentDetailsCopyWithImpl<$Res, PaymentDetails>; + @useResult + $Res call({String description}); +} + +/// @nodoc +class _$PaymentDetailsCopyWithImpl<$Res, $Val extends PaymentDetails> + implements $PaymentDetailsCopyWith<$Res> { + _$PaymentDetailsCopyWithImpl(this._value, this._then); + + // ignore: unused_field + final $Val _value; + // ignore: unused_field + final $Res Function($Val) _then; + + /// Create a copy of PaymentDetails + /// with the given fields replaced by the non-null parameter values. + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? description = null, + }) { + return _then(_value.copyWith( + description: null == description + ? _value.description + : description // ignore: cast_nullable_to_non_nullable + as String, + ) as $Val); + } +} + +/// @nodoc +abstract class _$$PaymentDetails_LightningImplCopyWith<$Res> implements $PaymentDetailsCopyWith<$Res> { + factory _$$PaymentDetails_LightningImplCopyWith( + _$PaymentDetails_LightningImpl value, $Res Function(_$PaymentDetails_LightningImpl) then) = + __$$PaymentDetails_LightningImplCopyWithImpl<$Res>; + @override + @useResult + $Res call( + {String swapId, + String description, + String? preimage, + String? bolt11, + String? refundTxId, + BigInt? refundTxAmountSat}); +} + +/// @nodoc +class __$$PaymentDetails_LightningImplCopyWithImpl<$Res> + extends _$PaymentDetailsCopyWithImpl<$Res, _$PaymentDetails_LightningImpl> + implements _$$PaymentDetails_LightningImplCopyWith<$Res> { + __$$PaymentDetails_LightningImplCopyWithImpl( + _$PaymentDetails_LightningImpl _value, $Res Function(_$PaymentDetails_LightningImpl) _then) + : super(_value, _then); + + /// Create a copy of PaymentDetails + /// with the given fields replaced by the non-null parameter values. + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? swapId = null, + Object? description = null, + Object? preimage = freezed, + Object? bolt11 = freezed, + Object? refundTxId = freezed, + Object? refundTxAmountSat = freezed, + }) { + return _then(_$PaymentDetails_LightningImpl( + swapId: null == swapId + ? _value.swapId + : swapId // ignore: cast_nullable_to_non_nullable + as String, + description: null == description + ? _value.description + : description // ignore: cast_nullable_to_non_nullable + as String, + preimage: freezed == preimage + ? _value.preimage + : preimage // ignore: cast_nullable_to_non_nullable + as String?, + bolt11: freezed == bolt11 + ? _value.bolt11 + : bolt11 // ignore: cast_nullable_to_non_nullable + as String?, + refundTxId: freezed == refundTxId + ? _value.refundTxId + : refundTxId // ignore: cast_nullable_to_non_nullable + as String?, + refundTxAmountSat: freezed == refundTxAmountSat + ? _value.refundTxAmountSat + : refundTxAmountSat // ignore: cast_nullable_to_non_nullable + as BigInt?, + )); + } +} + +/// @nodoc + +class _$PaymentDetails_LightningImpl extends PaymentDetails_Lightning { + const _$PaymentDetails_LightningImpl( + {required this.swapId, + required this.description, + this.preimage, + this.bolt11, + this.refundTxId, + this.refundTxAmountSat}) + : super._(); + + @override + final String swapId; + + /// Represents the invoice description + @override + final String description; + + /// In case of a Send swap, this is the preimage of the paid invoice (proof of payment). + @override + final String? preimage; + + /// Represents the invoice associated with a payment + /// In the case of a Send payment, this is the invoice paid by the swapper + /// In the case of a Receive payment, this is the invoice paid by the user + @override + final String? bolt11; + + /// For a Send swap which was refunded, this is the refund tx id + @override + final String? refundTxId; + + /// For a Send swap which was refunded, this is the refund amount + @override + final BigInt? refundTxAmountSat; + + @override + String toString() { + return 'PaymentDetails.lightning(swapId: $swapId, description: $description, preimage: $preimage, bolt11: $bolt11, refundTxId: $refundTxId, refundTxAmountSat: $refundTxAmountSat)'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _$PaymentDetails_LightningImpl && + (identical(other.swapId, swapId) || other.swapId == swapId) && + (identical(other.description, description) || other.description == description) && + (identical(other.preimage, preimage) || other.preimage == preimage) && + (identical(other.bolt11, bolt11) || other.bolt11 == bolt11) && + (identical(other.refundTxId, refundTxId) || other.refundTxId == refundTxId) && + (identical(other.refundTxAmountSat, refundTxAmountSat) || + other.refundTxAmountSat == refundTxAmountSat)); + } + + @override + int get hashCode => + Object.hash(runtimeType, swapId, description, preimage, bolt11, refundTxId, refundTxAmountSat); + + /// Create a copy of PaymentDetails + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + @override + @pragma('vm:prefer-inline') + _$$PaymentDetails_LightningImplCopyWith<_$PaymentDetails_LightningImpl> get copyWith => + __$$PaymentDetails_LightningImplCopyWithImpl<_$PaymentDetails_LightningImpl>(this, _$identity); +} + +abstract class PaymentDetails_Lightning extends PaymentDetails { + const factory PaymentDetails_Lightning( + {required final String swapId, + required final String description, + final String? preimage, + final String? bolt11, + final String? refundTxId, + final BigInt? refundTxAmountSat}) = _$PaymentDetails_LightningImpl; + const PaymentDetails_Lightning._() : super._(); + + String get swapId; + + /// Represents the invoice description + @override + String get description; + + /// In case of a Send swap, this is the preimage of the paid invoice (proof of payment). + String? get preimage; + + /// Represents the invoice associated with a payment + /// In the case of a Send payment, this is the invoice paid by the swapper + /// In the case of a Receive payment, this is the invoice paid by the user + String? get bolt11; + + /// For a Send swap which was refunded, this is the refund tx id + String? get refundTxId; + + /// For a Send swap which was refunded, this is the refund amount + BigInt? get refundTxAmountSat; + + /// Create a copy of PaymentDetails + /// with the given fields replaced by the non-null parameter values. + @override + @JsonKey(includeFromJson: false, includeToJson: false) + _$$PaymentDetails_LightningImplCopyWith<_$PaymentDetails_LightningImpl> get copyWith => + throw _privateConstructorUsedError; +} + +/// @nodoc +abstract class _$$PaymentDetails_LiquidImplCopyWith<$Res> implements $PaymentDetailsCopyWith<$Res> { + factory _$$PaymentDetails_LiquidImplCopyWith( + _$PaymentDetails_LiquidImpl value, $Res Function(_$PaymentDetails_LiquidImpl) then) = + __$$PaymentDetails_LiquidImplCopyWithImpl<$Res>; + @override + @useResult + $Res call({String destination, String description}); +} + +/// @nodoc +class __$$PaymentDetails_LiquidImplCopyWithImpl<$Res> + extends _$PaymentDetailsCopyWithImpl<$Res, _$PaymentDetails_LiquidImpl> + implements _$$PaymentDetails_LiquidImplCopyWith<$Res> { + __$$PaymentDetails_LiquidImplCopyWithImpl( + _$PaymentDetails_LiquidImpl _value, $Res Function(_$PaymentDetails_LiquidImpl) _then) + : super(_value, _then); + + /// Create a copy of PaymentDetails + /// with the given fields replaced by the non-null parameter values. + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? destination = null, + Object? description = null, + }) { + return _then(_$PaymentDetails_LiquidImpl( + destination: null == destination + ? _value.destination + : destination // ignore: cast_nullable_to_non_nullable + as String, + description: null == description + ? _value.description + : description // ignore: cast_nullable_to_non_nullable + as String, + )); + } +} + +/// @nodoc + +class _$PaymentDetails_LiquidImpl extends PaymentDetails_Liquid { + const _$PaymentDetails_LiquidImpl({required this.destination, required this.description}) : super._(); + + /// Represents either a Liquid BIP21 URI or pure address + @override + final String destination; + + /// Represents the BIP21 `message` field + @override + final String description; + + @override + String toString() { + return 'PaymentDetails.liquid(destination: $destination, description: $description)'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _$PaymentDetails_LiquidImpl && + (identical(other.destination, destination) || other.destination == destination) && + (identical(other.description, description) || other.description == description)); + } + + @override + int get hashCode => Object.hash(runtimeType, destination, description); + + /// Create a copy of PaymentDetails + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + @override + @pragma('vm:prefer-inline') + _$$PaymentDetails_LiquidImplCopyWith<_$PaymentDetails_LiquidImpl> get copyWith => + __$$PaymentDetails_LiquidImplCopyWithImpl<_$PaymentDetails_LiquidImpl>(this, _$identity); +} + +abstract class PaymentDetails_Liquid extends PaymentDetails { + const factory PaymentDetails_Liquid( + {required final String destination, required final String description}) = _$PaymentDetails_LiquidImpl; + const PaymentDetails_Liquid._() : super._(); + + /// Represents either a Liquid BIP21 URI or pure address + String get destination; + + /// Represents the BIP21 `message` field + @override + String get description; + + /// Create a copy of PaymentDetails + /// with the given fields replaced by the non-null parameter values. + @override + @JsonKey(includeFromJson: false, includeToJson: false) + _$$PaymentDetails_LiquidImplCopyWith<_$PaymentDetails_LiquidImpl> get copyWith => + throw _privateConstructorUsedError; +} + +/// @nodoc +abstract class _$$PaymentDetails_BitcoinImplCopyWith<$Res> implements $PaymentDetailsCopyWith<$Res> { + factory _$$PaymentDetails_BitcoinImplCopyWith( + _$PaymentDetails_BitcoinImpl value, $Res Function(_$PaymentDetails_BitcoinImpl) then) = + __$$PaymentDetails_BitcoinImplCopyWithImpl<$Res>; + @override + @useResult + $Res call({String swapId, String description, String? refundTxId, BigInt? refundTxAmountSat}); +} + +/// @nodoc +class __$$PaymentDetails_BitcoinImplCopyWithImpl<$Res> + extends _$PaymentDetailsCopyWithImpl<$Res, _$PaymentDetails_BitcoinImpl> + implements _$$PaymentDetails_BitcoinImplCopyWith<$Res> { + __$$PaymentDetails_BitcoinImplCopyWithImpl( + _$PaymentDetails_BitcoinImpl _value, $Res Function(_$PaymentDetails_BitcoinImpl) _then) + : super(_value, _then); + + /// Create a copy of PaymentDetails + /// with the given fields replaced by the non-null parameter values. + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? swapId = null, + Object? description = null, + Object? refundTxId = freezed, + Object? refundTxAmountSat = freezed, + }) { + return _then(_$PaymentDetails_BitcoinImpl( + swapId: null == swapId + ? _value.swapId + : swapId // ignore: cast_nullable_to_non_nullable + as String, + description: null == description + ? _value.description + : description // ignore: cast_nullable_to_non_nullable + as String, + refundTxId: freezed == refundTxId + ? _value.refundTxId + : refundTxId // ignore: cast_nullable_to_non_nullable + as String?, + refundTxAmountSat: freezed == refundTxAmountSat + ? _value.refundTxAmountSat + : refundTxAmountSat // ignore: cast_nullable_to_non_nullable + as BigInt?, + )); + } +} + +/// @nodoc + +class _$PaymentDetails_BitcoinImpl extends PaymentDetails_Bitcoin { + const _$PaymentDetails_BitcoinImpl( + {required this.swapId, required this.description, this.refundTxId, this.refundTxAmountSat}) + : super._(); + + @override + final String swapId; + + /// Represents the invoice description + @override + final String description; + + /// For a Send swap which was refunded, this is the refund tx id + @override + final String? refundTxId; + + /// For a Send swap which was refunded, this is the refund amount + @override + final BigInt? refundTxAmountSat; + + @override + String toString() { + return 'PaymentDetails.bitcoin(swapId: $swapId, description: $description, refundTxId: $refundTxId, refundTxAmountSat: $refundTxAmountSat)'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _$PaymentDetails_BitcoinImpl && + (identical(other.swapId, swapId) || other.swapId == swapId) && + (identical(other.description, description) || other.description == description) && + (identical(other.refundTxId, refundTxId) || other.refundTxId == refundTxId) && + (identical(other.refundTxAmountSat, refundTxAmountSat) || + other.refundTxAmountSat == refundTxAmountSat)); + } + + @override + int get hashCode => Object.hash(runtimeType, swapId, description, refundTxId, refundTxAmountSat); + + /// Create a copy of PaymentDetails + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + @override + @pragma('vm:prefer-inline') + _$$PaymentDetails_BitcoinImplCopyWith<_$PaymentDetails_BitcoinImpl> get copyWith => + __$$PaymentDetails_BitcoinImplCopyWithImpl<_$PaymentDetails_BitcoinImpl>(this, _$identity); +} + +abstract class PaymentDetails_Bitcoin extends PaymentDetails { + const factory PaymentDetails_Bitcoin( + {required final String swapId, + required final String description, + final String? refundTxId, + final BigInt? refundTxAmountSat}) = _$PaymentDetails_BitcoinImpl; + const PaymentDetails_Bitcoin._() : super._(); + + String get swapId; + + /// Represents the invoice description + @override + String get description; + + /// For a Send swap which was refunded, this is the refund tx id + String? get refundTxId; + + /// For a Send swap which was refunded, this is the refund amount + BigInt? get refundTxAmountSat; + + /// Create a copy of PaymentDetails + /// with the given fields replaced by the non-null parameter values. + @override + @JsonKey(includeFromJson: false, includeToJson: false) + _$$PaymentDetails_BitcoinImplCopyWith<_$PaymentDetails_BitcoinImpl> get copyWith => + throw _privateConstructorUsedError; +} + /// @nodoc mixin _$SdkEvent {} @@ -825,3 +1268,186 @@ abstract class SdkEvent_Synced extends SdkEvent { const factory SdkEvent_Synced() = _$SdkEvent_SyncedImpl; const SdkEvent_Synced._() : super._(); } + +/// @nodoc +mixin _$SendDestination {} + +/// @nodoc +abstract class $SendDestinationCopyWith<$Res> { + factory $SendDestinationCopyWith(SendDestination value, $Res Function(SendDestination) then) = + _$SendDestinationCopyWithImpl<$Res, SendDestination>; +} + +/// @nodoc +class _$SendDestinationCopyWithImpl<$Res, $Val extends SendDestination> + implements $SendDestinationCopyWith<$Res> { + _$SendDestinationCopyWithImpl(this._value, this._then); + + // ignore: unused_field + final $Val _value; + // ignore: unused_field + final $Res Function($Val) _then; + + /// Create a copy of SendDestination + /// with the given fields replaced by the non-null parameter values. +} + +/// @nodoc +abstract class _$$SendDestination_LiquidAddressImplCopyWith<$Res> { + factory _$$SendDestination_LiquidAddressImplCopyWith(_$SendDestination_LiquidAddressImpl value, + $Res Function(_$SendDestination_LiquidAddressImpl) then) = + __$$SendDestination_LiquidAddressImplCopyWithImpl<$Res>; + @useResult + $Res call({LiquidAddressData addressData}); +} + +/// @nodoc +class __$$SendDestination_LiquidAddressImplCopyWithImpl<$Res> + extends _$SendDestinationCopyWithImpl<$Res, _$SendDestination_LiquidAddressImpl> + implements _$$SendDestination_LiquidAddressImplCopyWith<$Res> { + __$$SendDestination_LiquidAddressImplCopyWithImpl( + _$SendDestination_LiquidAddressImpl _value, $Res Function(_$SendDestination_LiquidAddressImpl) _then) + : super(_value, _then); + + /// Create a copy of SendDestination + /// with the given fields replaced by the non-null parameter values. + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? addressData = null, + }) { + return _then(_$SendDestination_LiquidAddressImpl( + addressData: null == addressData + ? _value.addressData + : addressData // ignore: cast_nullable_to_non_nullable + as LiquidAddressData, + )); + } +} + +/// @nodoc + +class _$SendDestination_LiquidAddressImpl extends SendDestination_LiquidAddress { + const _$SendDestination_LiquidAddressImpl({required this.addressData}) : super._(); + + @override + final LiquidAddressData addressData; + + @override + String toString() { + return 'SendDestination.liquidAddress(addressData: $addressData)'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _$SendDestination_LiquidAddressImpl && + (identical(other.addressData, addressData) || other.addressData == addressData)); + } + + @override + int get hashCode => Object.hash(runtimeType, addressData); + + /// Create a copy of SendDestination + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + @override + @pragma('vm:prefer-inline') + _$$SendDestination_LiquidAddressImplCopyWith<_$SendDestination_LiquidAddressImpl> get copyWith => + __$$SendDestination_LiquidAddressImplCopyWithImpl<_$SendDestination_LiquidAddressImpl>( + this, _$identity); +} + +abstract class SendDestination_LiquidAddress extends SendDestination { + const factory SendDestination_LiquidAddress({required final LiquidAddressData addressData}) = + _$SendDestination_LiquidAddressImpl; + const SendDestination_LiquidAddress._() : super._(); + + LiquidAddressData get addressData; + + /// Create a copy of SendDestination + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + _$$SendDestination_LiquidAddressImplCopyWith<_$SendDestination_LiquidAddressImpl> get copyWith => + throw _privateConstructorUsedError; +} + +/// @nodoc +abstract class _$$SendDestination_Bolt11ImplCopyWith<$Res> { + factory _$$SendDestination_Bolt11ImplCopyWith( + _$SendDestination_Bolt11Impl value, $Res Function(_$SendDestination_Bolt11Impl) then) = + __$$SendDestination_Bolt11ImplCopyWithImpl<$Res>; + @useResult + $Res call({LNInvoice invoice}); +} + +/// @nodoc +class __$$SendDestination_Bolt11ImplCopyWithImpl<$Res> + extends _$SendDestinationCopyWithImpl<$Res, _$SendDestination_Bolt11Impl> + implements _$$SendDestination_Bolt11ImplCopyWith<$Res> { + __$$SendDestination_Bolt11ImplCopyWithImpl( + _$SendDestination_Bolt11Impl _value, $Res Function(_$SendDestination_Bolt11Impl) _then) + : super(_value, _then); + + /// Create a copy of SendDestination + /// with the given fields replaced by the non-null parameter values. + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? invoice = null, + }) { + return _then(_$SendDestination_Bolt11Impl( + invoice: null == invoice + ? _value.invoice + : invoice // ignore: cast_nullable_to_non_nullable + as LNInvoice, + )); + } +} + +/// @nodoc + +class _$SendDestination_Bolt11Impl extends SendDestination_Bolt11 { + const _$SendDestination_Bolt11Impl({required this.invoice}) : super._(); + + @override + final LNInvoice invoice; + + @override + String toString() { + return 'SendDestination.bolt11(invoice: $invoice)'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _$SendDestination_Bolt11Impl && + (identical(other.invoice, invoice) || other.invoice == invoice)); + } + + @override + int get hashCode => Object.hash(runtimeType, invoice); + + /// Create a copy of SendDestination + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + @override + @pragma('vm:prefer-inline') + _$$SendDestination_Bolt11ImplCopyWith<_$SendDestination_Bolt11Impl> get copyWith => + __$$SendDestination_Bolt11ImplCopyWithImpl<_$SendDestination_Bolt11Impl>(this, _$identity); +} + +abstract class SendDestination_Bolt11 extends SendDestination { + const factory SendDestination_Bolt11({required final LNInvoice invoice}) = _$SendDestination_Bolt11Impl; + const SendDestination_Bolt11._() : super._(); + + LNInvoice get invoice; + + /// Create a copy of SendDestination + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + _$$SendDestination_Bolt11ImplCopyWith<_$SendDestination_Bolt11Impl> get copyWith => + throw _privateConstructorUsedError; +} diff --git a/packages/flutter/example/lib/routes/connect/connect_page.dart b/packages/flutter/example/lib/routes/connect/connect_page.dart index 9d5e1ac..7e020aa 100644 --- a/packages/flutter/example/lib/routes/connect/connect_page.dart +++ b/packages/flutter/example/lib/routes/connect/connect_page.dart @@ -80,17 +80,21 @@ class _ConnectPageState extends State { debugPrint("${mnemonic.isEmpty ? "Creating" : "Restoring"} wallet with $walletMnemonic"); return await initializeWallet(mnemonic: walletMnemonic).then( (liquidSDK) async { - await widget.credentialsManager.storeMnemonic(mnemonic: walletMnemonic).then((_) { - Navigator.pushReplacement( - context, - MaterialPageRoute( - builder: (BuildContext context) => HomePage( - liquidSDK: widget.liquidSDK, - credentialsManager: widget.credentialsManager, - ), - ), - ); - }); + await widget.credentialsManager.storeMnemonic(mnemonic: walletMnemonic).then( + (_) { + if (mounted) { + Navigator.pushReplacement( + context, + MaterialPageRoute( + builder: (BuildContext context) => HomePage( + liquidSDK: widget.liquidSDK, + credentialsManager: widget.credentialsManager, + ), + ), + ); + } + }, + ); }, ); } diff --git a/packages/flutter/example/lib/routes/home/widgets/drawer.dart b/packages/flutter/example/lib/routes/home/widgets/drawer.dart index 5701a99..c41bb62 100644 --- a/packages/flutter/example/lib/routes/home/widgets/drawer.dart +++ b/packages/flutter/example/lib/routes/home/widgets/drawer.dart @@ -7,7 +7,11 @@ class HomePageDrawer extends StatefulWidget { final BindingLiquidSdk liquidSDK; final CredentialsManager credentialsManager; - const HomePageDrawer({super.key, required this.liquidSDK, required this.credentialsManager}); + const HomePageDrawer({ + super.key, + required this.liquidSDK, + required this.credentialsManager, + }); @override State createState() => _HomePageDrawerState(); @@ -32,8 +36,11 @@ class _HomePageDrawerState extends State { enabled: false, leading: const Icon(Icons.backup_outlined), title: const Text('Backup'), - titleTextStyle: - const TextStyle(fontSize: 16.0, color: Colors.white, decoration: TextDecoration.lineThrough), + titleTextStyle: const TextStyle( + fontSize: 16.0, + color: Colors.white, + decoration: TextDecoration.lineThrough, + ), onTap: () async { try { debugPrint("Creating backup."); @@ -44,7 +51,10 @@ class _HomePageDrawerState extends State { final errMsg = "Failed to create backup. $e"; debugPrint(errMsg); if (context.mounted) { - final snackBar = SnackBar(behavior: SnackBarBehavior.floating, content: Text(errMsg)); + final snackBar = SnackBar( + behavior: SnackBarBehavior.floating, + content: Text(errMsg), + ); ScaffoldMessenger.of(context).showSnackBar(snackBar); } } @@ -54,8 +64,11 @@ class _HomePageDrawerState extends State { enabled: false, leading: const Icon(Icons.restore), title: const Text('Restore'), - titleTextStyle: - const TextStyle(fontSize: 16.0, color: Colors.white, decoration: TextDecoration.lineThrough), + titleTextStyle: const TextStyle( + fontSize: 16.0, + color: Colors.white, + decoration: TextDecoration.lineThrough, + ), onTap: () async { try { debugPrint("Restoring backup."); @@ -67,7 +80,10 @@ class _HomePageDrawerState extends State { final errMsg = "Failed to restore backup. $e"; debugPrint(errMsg); if (context.mounted) { - final snackBar = SnackBar(behavior: SnackBarBehavior.floating, content: Text(errMsg)); + final snackBar = SnackBar( + behavior: SnackBarBehavior.floating, + content: Text(errMsg), + ); ScaffoldMessenger.of(context).showSnackBar(snackBar); } } @@ -86,7 +102,10 @@ class _HomePageDrawerState extends State { final errMsg = "Failed to empty wallet cache. $e"; debugPrint(errMsg); if (context.mounted) { - final snackBar = SnackBar(behavior: SnackBarBehavior.floating, content: Text(errMsg)); + final snackBar = SnackBar( + behavior: SnackBarBehavior.floating, + content: Text(errMsg), + ); ScaffoldMessenger.of(context).showSnackBar(snackBar); } } @@ -98,19 +117,26 @@ class _HomePageDrawerState extends State { titleTextStyle: const TextStyle(fontSize: 16.0, color: Colors.white), onTap: () async { try { - await widget.credentialsManager.restoreMnemonic().then((mnemonics) { - showDialog( - context: context, - builder: (context) => MnemonicsDialog( - mnemonics: mnemonics.split(" "), - ), - ); - }); + await widget.credentialsManager.restoreMnemonic().then( + (mnemonics) { + if (context.mounted) { + showDialog( + context: context, + builder: (context) => MnemonicsDialog( + mnemonics: mnemonics.split(" "), + ), + ); + } + }, + ); } on Exception catch (e) { final errMsg = "Failed to display mnemonics. $e"; debugPrint(errMsg); if (context.mounted) { - final snackBar = SnackBar(behavior: SnackBarBehavior.floating, content: Text(errMsg)); + final snackBar = SnackBar( + behavior: SnackBarBehavior.floating, + content: Text(errMsg), + ); ScaffoldMessenger.of(context).showSnackBar(snackBar); } } diff --git a/packages/flutter/example/lib/routes/home/widgets/payment_list/widgets/payment_item.dart b/packages/flutter/example/lib/routes/home/widgets/payment_list/widgets/payment_item.dart index c86f474..c73de76 100644 --- a/packages/flutter/example/lib/routes/home/widgets/payment_list/widgets/payment_item.dart +++ b/packages/flutter/example/lib/routes/home/widgets/payment_list/widgets/payment_item.dart @@ -10,43 +10,7 @@ class PaymentItem extends StatelessWidget { @override Widget build(BuildContext context) { return ListTile( - onLongPress: item.preimage != null - ? () { - try { - debugPrint("Store payment preimage on clipboard. Preimage: ${item.preimage!}"); - Clipboard.setData(ClipboardData(text: item.preimage!)); - const snackBar = SnackBar( - behavior: SnackBarBehavior.floating, - content: Text('Copied payment preimage to clipboard.'), - ); - ScaffoldMessenger.of(context).showSnackBar(snackBar); - } catch (e) { - final snackBar = SnackBar( - behavior: SnackBarBehavior.floating, - content: Text('Failed to copy payment preimage to clipboard. $e'), - ); - ScaffoldMessenger.of(context).showSnackBar(snackBar); - } - } - : item.swapId != null - ? () { - try { - debugPrint("Store swap ID on clipboard. Swap ID: ${item.swapId!}"); - Clipboard.setData(ClipboardData(text: item.swapId!)); - const snackBar = SnackBar( - behavior: SnackBarBehavior.floating, - content: Text('Copied swap ID to clipboard.'), - ); - ScaffoldMessenger.of(context).showSnackBar(snackBar); - } catch (e) { - final snackBar = SnackBar( - behavior: SnackBarBehavior.floating, - content: Text('Failed to copy payment preimage to clipboard. $e'), - ); - ScaffoldMessenger.of(context).showSnackBar(snackBar); - } - } - : null, + onLongPress: () => _onLongPress(context), title: Text(_paymentTitle(item)), subtitle: Text( DateFormat('dd/MM/yyyy, HH:mm').format( @@ -70,6 +34,67 @@ class PaymentItem extends StatelessWidget { ); } + void _onLongPress(BuildContext context) { + final details = item.details; + if (details == null) return; + + if (details is PaymentDetails_Lightning && details.preimage != null) { + try { + debugPrint("Store payment preimage on clipboard. Preimage: ${details.preimage!}"); + Clipboard.setData(ClipboardData(text: details.preimage!)); + const snackBar = SnackBar( + behavior: SnackBarBehavior.floating, + content: Text('Copied payment preimage to clipboard.'), + ); + ScaffoldMessenger.of(context).showSnackBar(snackBar); + } catch (e) { + final snackBar = SnackBar( + behavior: SnackBarBehavior.floating, + content: Text('Failed to copy payment preimage to clipboard. $e'), + ); + ScaffoldMessenger.of(context).showSnackBar(snackBar); + } + } + + if (details is PaymentDetails_Bitcoin) { + try { + debugPrint("Store swap ID on clipboard. Swap ID: ${details.swapId}"); + Clipboard.setData(ClipboardData(text: details.swapId)); + const snackBar = SnackBar( + behavior: SnackBarBehavior.floating, + content: Text('Copied swap ID to clipboard.'), + ); + ScaffoldMessenger.of(context).showSnackBar(snackBar); + } catch (e) { + final snackBar = SnackBar( + behavior: SnackBarBehavior.floating, + content: Text('Failed to copy payment swap ID to clipboard. $e'), + ); + ScaffoldMessenger.of(context).showSnackBar(snackBar); + } + } + + if (details is PaymentDetails_Liquid) { + try { + debugPrint("Store Liquid Address on clipboard. Liquid Address: ${details.destination}"); + Clipboard.setData(ClipboardData(text: details.destination)); + const snackBar = SnackBar( + behavior: SnackBarBehavior.floating, + content: Text('Copied Liquid Address to clipboard.'), + ); + ScaffoldMessenger.of(context).showSnackBar(snackBar); + } catch (e) { + final snackBar = SnackBar( + behavior: SnackBarBehavior.floating, + content: Text('Failed to copy payment Liquid Address to clipboard. $e'), + ); + ScaffoldMessenger.of(context).showSnackBar(snackBar); + } + } + + return; + } + String _paymentTitle(Payment payment) { final paymentType = payment.paymentType; diff --git a/packages/flutter/example/lib/routes/home/widgets/qr_scan/scanner_button_widgets.dart b/packages/flutter/example/lib/routes/home/widgets/qr_scan/scanner_button_widgets.dart index 42b72d8..21c37c2 100644 --- a/packages/flutter/example/lib/routes/home/widgets/qr_scan/scanner_button_widgets.dart +++ b/packages/flutter/example/lib/routes/home/widgets/qr_scan/scanner_button_widgets.dart @@ -153,7 +153,13 @@ class CancelScanButton extends StatelessWidget { ), ), onPressed: () async { - controller.stop().then((_) => Navigator.of(context).pop()); + controller.stop().then( + (_) { + if (context.mounted) { + Navigator.of(context).pop(); + } + }, + ); }, child: const Text( "CANCEL", diff --git a/packages/flutter/example/lib/routes/home/widgets/qr_scan_action_button.dart b/packages/flutter/example/lib/routes/home/widgets/qr_scan_action_button.dart index a734489..5831c99 100644 --- a/packages/flutter/example/lib/routes/home/widgets/qr_scan_action_button.dart +++ b/packages/flutter/example/lib/routes/home/widgets/qr_scan_action_button.dart @@ -34,10 +34,12 @@ class QrActionButton extends StatelessWidget { ).then((barcode) { if (barcode == null || barcode.isEmpty) return; debugPrint("Scanned string: '$barcode'"); - showDialog( - context: context, - builder: (context) => SendPaymentDialog(barcodeValue: barcode, liquidSdk: liquidSDK), - ); + if (context.mounted) { + showDialog( + context: context, + builder: (context) => SendPaymentDialog(barcodeValue: barcode, liquidSdk: liquidSDK), + ); + } }); } } diff --git a/packages/flutter/example/lib/routes/home/widgets/receive_payment/receive_payment_dialog.dart b/packages/flutter/example/lib/routes/home/widgets/receive_payment/receive_payment_dialog.dart index 29edb7f..d78525d 100644 --- a/packages/flutter/example/lib/routes/home/widgets/receive_payment/receive_payment_dialog.dart +++ b/packages/flutter/example/lib/routes/home/widgets/receive_payment/receive_payment_dialog.dart @@ -22,8 +22,7 @@ class _ReceivePaymentDialogState extends State { int? feesSat; bool creatingInvoice = false; - String? invoice; - String? invoiceId; + String? invoiceDestination; StreamSubscription>? streamSubscription; @@ -31,10 +30,19 @@ class _ReceivePaymentDialogState extends State { void initState() { super.initState(); streamSubscription = widget.paymentsStream.listen((paymentList) { - if (invoiceId != null && invoiceId!.isNotEmpty) { - if (paymentList.any((e) => e.swapId == invoiceId!)) { - debugPrint("Payment Received! Id: $invoiceId"); - if (context.mounted) { + if (invoiceDestination != null && invoiceDestination!.isNotEmpty) { + if (paymentList.any( + (e) { + final details = e.details; + if (details == null) return false; + if (details is PaymentDetails_Lightning && details.preimage != null) { + return details.preimage! == invoiceDestination!; + } + return false; + }, + )) { + debugPrint("Payment Received! Id: $invoiceDestination"); + if (mounted) { Navigator.of(context).pop(); } } @@ -51,13 +59,13 @@ class _ReceivePaymentDialogState extends State { @override Widget build(BuildContext context) { return AlertDialog( - title: creatingInvoice ? null : Text(invoice != null ? "Invoice" : "Receive Payment"), - content: creatingInvoice || invoice != null + title: creatingInvoice ? null : Text(invoiceDestination != null ? "Invoice" : "Receive Payment"), + content: creatingInvoice || invoiceDestination != null ? Column( mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.center, children: [ - if (invoice != null) ...[ + if (invoiceDestination != null) ...[ AspectRatio( aspectRatio: 1, child: SizedBox( @@ -65,7 +73,7 @@ class _ReceivePaymentDialogState extends State { height: 200.0, child: QrImageView( embeddedImage: const AssetImage("assets/icons/app_icon.png"), - data: invoice!.toUpperCase(), + data: invoiceDestination!.toUpperCase(), size: 200.0, ), ), @@ -128,34 +136,36 @@ class _ReceivePaymentDialogState extends State { Navigator.of(context).pop(); }, ), - if (invoice == null) ...[ + if (invoiceDestination == null) ...[ TextButton( onPressed: () async { try { setState(() => creatingInvoice = true); int amountSat = int.parse(payerAmountController.text); - PrepareReceivePaymentRequest prepareReceiveReq = - PrepareReceivePaymentRequest(payerAmountSat: BigInt.from(amountSat)); - PrepareReceivePaymentResponse prepareRes = await widget.liquidSDK.prepareReceivePayment( + PrepareReceiveRequest prepareReceiveReq = PrepareReceiveRequest( + paymentMethod: PaymentMethod.lightning, + payerAmountSat: BigInt.from(amountSat), + ); + PrepareReceiveResponse prepareResponse = await widget.liquidSDK.prepareReceivePayment( req: prepareReceiveReq, ); setState(() { - payerAmountSat = prepareRes.payerAmountSat.toInt(); - feesSat = prepareRes.feesSat.toInt(); + payerAmountSat = prepareResponse.payerAmountSat?.toInt(); + feesSat = prepareResponse.feesSat.toInt(); }); - ReceivePaymentRequest receiveReq = ReceivePaymentRequest(prepareRes: prepareRes); + ReceivePaymentRequest receiveReq = ReceivePaymentRequest( + prepareResponse: prepareResponse, + ); ReceivePaymentResponse resp = await widget.liquidSDK.receivePayment(req: receiveReq); debugPrint( - "Created Invoice for $payerAmountSat sats with $feesSat sats fees.\nInvoice:${resp.invoice}", + "Created Invoice for $payerAmountSat sats with $feesSat sats fees.\nDestination:${resp.destination}", ); - setState(() => invoice = resp.invoice); - setState(() => invoiceId = resp.id); + setState(() => invoiceDestination = resp.destination); } catch (e) { setState(() { payerAmountSat = null; feesSat = null; - invoice = null; - invoiceId = null; + invoiceDestination = null; }); final errMsg = "Error receiving payment: $e"; debugPrint(errMsg); diff --git a/packages/flutter/example/lib/routes/home/widgets/send_payment/send_payment_dialog.dart b/packages/flutter/example/lib/routes/home/widgets/send_payment/send_payment_dialog.dart index 6b86c84..e3a7c76 100644 --- a/packages/flutter/example/lib/routes/home/widgets/send_payment/send_payment_dialog.dart +++ b/packages/flutter/example/lib/routes/home/widgets/send_payment/send_payment_dialog.dart @@ -17,7 +17,7 @@ class _SendPaymentDialogState extends State { bool paymentInProgress = false; - PrepareSendResponse? sendPaymentReq; + SendPaymentRequest? sendPaymentReq; @override void initState() { @@ -50,7 +50,7 @@ class _SendPaymentDialogState extends State { mainAxisSize: MainAxisSize.min, children: [ Text( - 'Please confirm that you agree to the payment fee of ${sendPaymentReq!.feesSat} sats.', + 'Please confirm that you agree to the payment fee of ${sendPaymentReq!.prepareResponse.feesSat} sats.', ), ], ), @@ -84,12 +84,16 @@ class _SendPaymentDialogState extends State { onPressed: () async { try { setState(() => paymentInProgress = true); - PrepareSendRequest prepareSendReq = - PrepareSendRequest(invoice: invoiceController.text); - PrepareSendResponse req = - await widget.liquidSdk.prepareSendPayment(req: prepareSendReq); - debugPrint("PrepareSendResponse for ${req.invoice}, fees: ${req.feesSat}"); - setState(() => sendPaymentReq = req); + PrepareSendRequest prepareSendReq = PrepareSendRequest( + destination: invoiceController.text, + ); + PrepareSendResponse req = await widget.liquidSdk.prepareSendPayment( + req: prepareSendReq, + ); + debugPrint( + "PrepareSendResponse for ${req.destination}, fees: ${req.feesSat}", + ); + setState(() => sendPaymentReq = SendPaymentRequest(prepareResponse: req)); } catch (e) { final errMsg = "Error preparing payment: $e"; debugPrint(errMsg); diff --git a/packages/flutter/example/lib/services/breez_sdk_liquid.dart b/packages/flutter/example/lib/services/breez_sdk_liquid.dart index fa50a55..948222c 100644 --- a/packages/flutter/example/lib/services/breez_sdk_liquid.dart +++ b/packages/flutter/example/lib/services/breez_sdk_liquid.dart @@ -106,37 +106,37 @@ class BreezSDKLiquid { (event) async { if (event is liquid_sdk.SdkEvent_PaymentFailed) { _logStreamController.add( - liquid_sdk.LogEntry(line: "Payment Failed. ${event.details.swapId}", level: "WARN"), + liquid_sdk.LogEntry(line: "Payment Failed. ${event.details}", level: "WARN"), ); _paymentResultStream.addError(PaymentException(event.details)); } if (event is liquid_sdk.SdkEvent_PaymentPending) { _logStreamController.add( - liquid_sdk.LogEntry(line: "Payment Pending. ${event.details.swapId}", level: "INFO"), + liquid_sdk.LogEntry(line: "Payment Pending. ${event.details}", level: "INFO"), ); _paymentResultStream.add(event.details); } if (event is liquid_sdk.SdkEvent_PaymentRefunded) { _logStreamController.add( - liquid_sdk.LogEntry(line: "Payment Refunded. ${event.details.swapId}", level: "INFO"), + liquid_sdk.LogEntry(line: "Payment Refunded. ${event.details}", level: "INFO"), ); _paymentResultStream.add(event.details); } if (event is liquid_sdk.SdkEvent_PaymentRefundPending) { _logStreamController.add( - liquid_sdk.LogEntry(line: "Pending Payment Refund. ${event.details.swapId}", level: "INFO"), + liquid_sdk.LogEntry(line: "Pending Payment Refund. ${event.details}", level: "INFO"), ); _paymentResultStream.add(event.details); } if (event is liquid_sdk.SdkEvent_PaymentSucceeded) { _logStreamController.add( - liquid_sdk.LogEntry(line: "Payment Succeeded. ${event.details.swapId}", level: "INFO"), + liquid_sdk.LogEntry(line: "Payment Succeeded. ${event.details}", level: "INFO"), ); _paymentResultStream.add(event.details); } if (event is liquid_sdk.SdkEvent_PaymentWaitingConfirmation) { _logStreamController.add( - liquid_sdk.LogEntry(line: "Payment Waiting Confirmation. ${event.details.swapId}", level: "INFO"), + liquid_sdk.LogEntry(line: "Payment Waiting Confirmation. ${event.details}", level: "INFO"), ); _paymentResultStream.add(event.details); } diff --git a/packages/flutter/example/pubspec.lock b/packages/flutter/example/pubspec.lock index c0268c6..f54cf9e 100644 --- a/packages/flutter/example/pubspec.lock +++ b/packages/flutter/example/pubspec.lock @@ -330,10 +330,10 @@ packages: dependency: "direct main" description: name: mobile_scanner - sha256: b8c0e9afcfd52534f85ec666f3d52156f560b5e6c25b1e3d4fe2087763607926 + sha256: "6ac2913ad98c83f558d2c8a55bc8f511bdcf28b86639701c04b04c16da1e9ee1" url: "https://pub.dev" source: hosted - version: "5.1.1" + version: "5.2.1" package_config: dependency: transitive description: diff --git a/packages/flutter/lib/flutter_breez_liquid_bindings_generated.dart b/packages/flutter/lib/flutter_breez_liquid_bindings_generated.dart index e761994..757c662 100644 --- a/packages/flutter/lib/flutter_breez_liquid_bindings_generated.dart +++ b/packages/flutter/lib/flutter_breez_liquid_bindings_generated.dart @@ -369,32 +369,10 @@ class FlutterBreezLiquidBindings { _frbgen_breez_liquid_wire__crate__bindings__BindingLiquidSdk_prepare_pay_onchainPtr .asFunction)>(); - void frbgen_breez_liquid_wire__crate__bindings__BindingLiquidSdk_prepare_receive_onchain( - int port_, - int that, - ffi.Pointer req, - ) { - return _frbgen_breez_liquid_wire__crate__bindings__BindingLiquidSdk_prepare_receive_onchain( - port_, - that, - req, - ); - } - - late final _frbgen_breez_liquid_wire__crate__bindings__BindingLiquidSdk_prepare_receive_onchainPtr = - _lookup< - ffi.NativeFunction< - ffi.Void Function( - ffi.Int64, ffi.UintPtr, ffi.Pointer)>>( - 'frbgen_breez_liquid_wire__crate__bindings__BindingLiquidSdk_prepare_receive_onchain'); - late final _frbgen_breez_liquid_wire__crate__bindings__BindingLiquidSdk_prepare_receive_onchain = - _frbgen_breez_liquid_wire__crate__bindings__BindingLiquidSdk_prepare_receive_onchainPtr - .asFunction)>(); - void frbgen_breez_liquid_wire__crate__bindings__BindingLiquidSdk_prepare_receive_payment( int port_, int that, - ffi.Pointer req, + ffi.Pointer req, ) { return _frbgen_breez_liquid_wire__crate__bindings__BindingLiquidSdk_prepare_receive_payment( port_, @@ -406,12 +384,11 @@ class FlutterBreezLiquidBindings { late final _frbgen_breez_liquid_wire__crate__bindings__BindingLiquidSdk_prepare_receive_paymentPtr = _lookup< ffi.NativeFunction< - ffi.Void Function( - ffi.Int64, ffi.UintPtr, ffi.Pointer)>>( + ffi.Void Function(ffi.Int64, ffi.UintPtr, ffi.Pointer)>>( 'frbgen_breez_liquid_wire__crate__bindings__BindingLiquidSdk_prepare_receive_payment'); late final _frbgen_breez_liquid_wire__crate__bindings__BindingLiquidSdk_prepare_receive_payment = _frbgen_breez_liquid_wire__crate__bindings__BindingLiquidSdk_prepare_receive_paymentPtr - .asFunction)>(); + .asFunction)>(); void frbgen_breez_liquid_wire__crate__bindings__BindingLiquidSdk_prepare_refund( int port_, @@ -453,27 +430,6 @@ class FlutterBreezLiquidBindings { _frbgen_breez_liquid_wire__crate__bindings__BindingLiquidSdk_prepare_send_paymentPtr .asFunction)>(); - void frbgen_breez_liquid_wire__crate__bindings__BindingLiquidSdk_receive_onchain( - int port_, - int that, - ffi.Pointer req, - ) { - return _frbgen_breez_liquid_wire__crate__bindings__BindingLiquidSdk_receive_onchain( - port_, - that, - req, - ); - } - - late final _frbgen_breez_liquid_wire__crate__bindings__BindingLiquidSdk_receive_onchainPtr = _lookup< - ffi.NativeFunction< - ffi.Void Function( - ffi.Int64, ffi.UintPtr, ffi.Pointer)>>( - 'frbgen_breez_liquid_wire__crate__bindings__BindingLiquidSdk_receive_onchain'); - late final _frbgen_breez_liquid_wire__crate__bindings__BindingLiquidSdk_receive_onchain = - _frbgen_breez_liquid_wire__crate__bindings__BindingLiquidSdk_receive_onchainPtr - .asFunction)>(); - void frbgen_breez_liquid_wire__crate__bindings__BindingLiquidSdk_receive_payment( int port_, int that, @@ -569,7 +525,7 @@ class FlutterBreezLiquidBindings { void frbgen_breez_liquid_wire__crate__bindings__BindingLiquidSdk_send_payment( int port_, int that, - ffi.Pointer req, + ffi.Pointer req, ) { return _frbgen_breez_liquid_wire__crate__bindings__BindingLiquidSdk_send_payment( port_, @@ -580,11 +536,11 @@ class FlutterBreezLiquidBindings { late final _frbgen_breez_liquid_wire__crate__bindings__BindingLiquidSdk_send_paymentPtr = _lookup< ffi.NativeFunction< - ffi.Void Function(ffi.Int64, ffi.UintPtr, ffi.Pointer)>>( + ffi.Void Function(ffi.Int64, ffi.UintPtr, ffi.Pointer)>>( 'frbgen_breez_liquid_wire__crate__bindings__BindingLiquidSdk_send_payment'); late final _frbgen_breez_liquid_wire__crate__bindings__BindingLiquidSdk_send_payment = _frbgen_breez_liquid_wire__crate__bindings__BindingLiquidSdk_send_paymentPtr - .asFunction)>(); + .asFunction)>(); void frbgen_breez_liquid_wire__crate__bindings__BindingLiquidSdk_sync( int port_, @@ -1020,6 +976,17 @@ class FlutterBreezLiquidBindings { _frbgen_breez_liquid_cst_new_box_autoadd_paymentPtr .asFunction Function()>(); + ffi.Pointer frbgen_breez_liquid_cst_new_box_autoadd_payment_details() { + return _frbgen_breez_liquid_cst_new_box_autoadd_payment_details(); + } + + late final _frbgen_breez_liquid_cst_new_box_autoadd_payment_detailsPtr = + _lookup Function()>>( + 'frbgen_breez_liquid_cst_new_box_autoadd_payment_details'); + late final _frbgen_breez_liquid_cst_new_box_autoadd_payment_details = + _frbgen_breez_liquid_cst_new_box_autoadd_payment_detailsPtr + .asFunction Function()>(); + ffi.Pointer frbgen_breez_liquid_cst_new_box_autoadd_prepare_buy_bitcoin_request() { return _frbgen_breez_liquid_cst_new_box_autoadd_prepare_buy_bitcoin_request(); @@ -1044,41 +1011,17 @@ class FlutterBreezLiquidBindings { _frbgen_breez_liquid_cst_new_box_autoadd_prepare_pay_onchain_requestPtr .asFunction Function()>(); - ffi.Pointer - frbgen_breez_liquid_cst_new_box_autoadd_prepare_receive_onchain_request() { - return _frbgen_breez_liquid_cst_new_box_autoadd_prepare_receive_onchain_request(); + ffi.Pointer + frbgen_breez_liquid_cst_new_box_autoadd_prepare_receive_request() { + return _frbgen_breez_liquid_cst_new_box_autoadd_prepare_receive_request(); } - late final _frbgen_breez_liquid_cst_new_box_autoadd_prepare_receive_onchain_requestPtr = - _lookup Function()>>( - 'frbgen_breez_liquid_cst_new_box_autoadd_prepare_receive_onchain_request'); - late final _frbgen_breez_liquid_cst_new_box_autoadd_prepare_receive_onchain_request = - _frbgen_breez_liquid_cst_new_box_autoadd_prepare_receive_onchain_requestPtr - .asFunction Function()>(); - - ffi.Pointer - frbgen_breez_liquid_cst_new_box_autoadd_prepare_receive_onchain_response() { - return _frbgen_breez_liquid_cst_new_box_autoadd_prepare_receive_onchain_response(); - } - - late final _frbgen_breez_liquid_cst_new_box_autoadd_prepare_receive_onchain_responsePtr = - _lookup Function()>>( - 'frbgen_breez_liquid_cst_new_box_autoadd_prepare_receive_onchain_response'); - late final _frbgen_breez_liquid_cst_new_box_autoadd_prepare_receive_onchain_response = - _frbgen_breez_liquid_cst_new_box_autoadd_prepare_receive_onchain_responsePtr - .asFunction Function()>(); - - ffi.Pointer - frbgen_breez_liquid_cst_new_box_autoadd_prepare_receive_payment_request() { - return _frbgen_breez_liquid_cst_new_box_autoadd_prepare_receive_payment_request(); - } - - late final _frbgen_breez_liquid_cst_new_box_autoadd_prepare_receive_payment_requestPtr = - _lookup Function()>>( - 'frbgen_breez_liquid_cst_new_box_autoadd_prepare_receive_payment_request'); - late final _frbgen_breez_liquid_cst_new_box_autoadd_prepare_receive_payment_request = - _frbgen_breez_liquid_cst_new_box_autoadd_prepare_receive_payment_requestPtr - .asFunction Function()>(); + late final _frbgen_breez_liquid_cst_new_box_autoadd_prepare_receive_requestPtr = + _lookup Function()>>( + 'frbgen_breez_liquid_cst_new_box_autoadd_prepare_receive_request'); + late final _frbgen_breez_liquid_cst_new_box_autoadd_prepare_receive_request = + _frbgen_breez_liquid_cst_new_box_autoadd_prepare_receive_requestPtr + .asFunction Function()>(); ffi.Pointer frbgen_breez_liquid_cst_new_box_autoadd_prepare_refund_request() { @@ -1103,18 +1046,6 @@ class FlutterBreezLiquidBindings { _frbgen_breez_liquid_cst_new_box_autoadd_prepare_send_requestPtr .asFunction Function()>(); - ffi.Pointer - frbgen_breez_liquid_cst_new_box_autoadd_prepare_send_response() { - return _frbgen_breez_liquid_cst_new_box_autoadd_prepare_send_response(); - } - - late final _frbgen_breez_liquid_cst_new_box_autoadd_prepare_send_responsePtr = - _lookup Function()>>( - 'frbgen_breez_liquid_cst_new_box_autoadd_prepare_send_response'); - late final _frbgen_breez_liquid_cst_new_box_autoadd_prepare_send_response = - _frbgen_breez_liquid_cst_new_box_autoadd_prepare_send_responsePtr - .asFunction Function()>(); - ffi.Pointer frbgen_breez_liquid_cst_new_box_autoadd_receive_payment_request() { return _frbgen_breez_liquid_cst_new_box_autoadd_receive_payment_request(); @@ -1160,6 +1091,17 @@ class FlutterBreezLiquidBindings { _frbgen_breez_liquid_cst_new_box_autoadd_sdk_eventPtr .asFunction Function()>(); + ffi.Pointer frbgen_breez_liquid_cst_new_box_autoadd_send_payment_request() { + return _frbgen_breez_liquid_cst_new_box_autoadd_send_payment_request(); + } + + late final _frbgen_breez_liquid_cst_new_box_autoadd_send_payment_requestPtr = + _lookup Function()>>( + 'frbgen_breez_liquid_cst_new_box_autoadd_send_payment_request'); + late final _frbgen_breez_liquid_cst_new_box_autoadd_send_payment_request = + _frbgen_breez_liquid_cst_new_box_autoadd_send_payment_requestPtr + .asFunction Function()>(); + ffi.Pointer frbgen_breez_liquid_cst_new_box_autoadd_success_action_processed() { return _frbgen_breez_liquid_cst_new_box_autoadd_success_action_processed(); @@ -1421,7 +1363,7 @@ final class wire_cst_prepare_buy_bitcoin_response extends ffi.Struct { } final class wire_cst_buy_bitcoin_request extends ffi.Struct { - external wire_cst_prepare_buy_bitcoin_response prepare_res; + external wire_cst_prepare_buy_bitcoin_response prepare_response; external ffi.Pointer redirect_url; } @@ -1529,7 +1471,7 @@ final class wire_cst_prepare_pay_onchain_response extends ffi.Struct { final class wire_cst_pay_onchain_request extends ffi.Struct { external ffi.Pointer address; - external wire_cst_prepare_pay_onchain_response prepare_res; + external wire_cst_prepare_pay_onchain_response prepare_response; } final class wire_cst_prepare_buy_bitcoin_request extends ffi.Struct { @@ -1547,14 +1489,11 @@ final class wire_cst_prepare_pay_onchain_request extends ffi.Struct { external ffi.Pointer sat_per_vbyte; } -final class wire_cst_prepare_receive_onchain_request extends ffi.Struct { - @ffi.Uint64() - external int payer_amount_sat; -} +final class wire_cst_prepare_receive_request extends ffi.Struct { + external ffi.Pointer payer_amount_sat; -final class wire_cst_prepare_receive_payment_request extends ffi.Struct { - @ffi.Uint64() - external int payer_amount_sat; + @ffi.Int32() + external int payment_method; } final class wire_cst_prepare_refund_request extends ffi.Struct { @@ -1567,20 +1506,16 @@ final class wire_cst_prepare_refund_request extends ffi.Struct { } final class wire_cst_prepare_send_request extends ffi.Struct { - external ffi.Pointer invoice; + external ffi.Pointer destination; + + external ffi.Pointer amount_sat; } -final class wire_cst_prepare_receive_onchain_response extends ffi.Struct { - @ffi.Uint64() - external int payer_amount_sat; +final class wire_cst_prepare_receive_response extends ffi.Struct { + @ffi.Int32() + external int payment_method; - @ffi.Uint64() - external int fees_sat; -} - -final class wire_cst_prepare_receive_payment_response extends ffi.Struct { - @ffi.Uint64() - external int payer_amount_sat; + external ffi.Pointer payer_amount_sat; @ffi.Uint64() external int fees_sat; @@ -1589,7 +1524,7 @@ final class wire_cst_prepare_receive_payment_response extends ffi.Struct { final class wire_cst_receive_payment_request extends ffi.Struct { external ffi.Pointer description; - external wire_cst_prepare_receive_payment_response prepare_res; + external wire_cst_prepare_receive_response prepare_response; } final class wire_cst_refund_request extends ffi.Struct { @@ -1605,22 +1540,175 @@ final class wire_cst_restore_request extends ffi.Struct { external ffi.Pointer backup_path; } +final class wire_cst_liquid_address_data extends ffi.Struct { + external ffi.Pointer address; + + @ffi.Int32() + external int network; + + external ffi.Pointer asset_id; + + external ffi.Pointer amount_sat; + + external ffi.Pointer label; + + external ffi.Pointer message; +} + +final class wire_cst_SendDestination_LiquidAddress extends ffi.Struct { + external ffi.Pointer address_data; +} + +final class wire_cst_route_hint_hop extends ffi.Struct { + external ffi.Pointer src_node_id; + + @ffi.Uint64() + external int short_channel_id; + + @ffi.Uint32() + external int fees_base_msat; + + @ffi.Uint32() + external int fees_proportional_millionths; + + @ffi.Uint64() + external int cltv_expiry_delta; + + external ffi.Pointer htlc_minimum_msat; + + external ffi.Pointer htlc_maximum_msat; +} + +final class wire_cst_list_route_hint_hop extends ffi.Struct { + external ffi.Pointer ptr; + + @ffi.Int32() + external int len; +} + +final class wire_cst_route_hint extends ffi.Struct { + external ffi.Pointer hops; +} + +final class wire_cst_list_route_hint extends ffi.Struct { + external ffi.Pointer ptr; + + @ffi.Int32() + external int len; +} + +final class wire_cst_ln_invoice extends ffi.Struct { + external ffi.Pointer bolt11; + + @ffi.Int32() + external int network; + + external ffi.Pointer payee_pubkey; + + external ffi.Pointer payment_hash; + + external ffi.Pointer description; + + external ffi.Pointer description_hash; + + external ffi.Pointer amount_msat; + + @ffi.Uint64() + external int timestamp; + + @ffi.Uint64() + external int expiry; + + external ffi.Pointer routing_hints; + + external ffi.Pointer payment_secret; + + @ffi.Uint64() + external int min_final_cltv_expiry_delta; +} + +final class wire_cst_SendDestination_Bolt11 extends ffi.Struct { + external ffi.Pointer invoice; +} + +final class SendDestinationKind extends ffi.Union { + external wire_cst_SendDestination_LiquidAddress LiquidAddress; + + external wire_cst_SendDestination_Bolt11 Bolt11; +} + +final class wire_cst_send_destination extends ffi.Struct { + @ffi.Int32() + external int tag; + + external SendDestinationKind kind; +} + final class wire_cst_prepare_send_response extends ffi.Struct { - external ffi.Pointer invoice; + external wire_cst_send_destination destination; @ffi.Uint64() external int fees_sat; } +final class wire_cst_send_payment_request extends ffi.Struct { + external wire_cst_prepare_send_response prepare_response; +} + final class wire_cst_binding_event_listener extends ffi.Struct { external ffi.Pointer stream; } -final class wire_cst_payment extends ffi.Struct { - external ffi.Pointer tx_id; - +final class wire_cst_PaymentDetails_Lightning extends ffi.Struct { external ffi.Pointer swap_id; + external ffi.Pointer description; + + external ffi.Pointer preimage; + + external ffi.Pointer bolt11; + + external ffi.Pointer refund_tx_id; + + external ffi.Pointer refund_tx_amount_sat; +} + +final class wire_cst_PaymentDetails_Liquid extends ffi.Struct { + external ffi.Pointer destination; + + external ffi.Pointer description; +} + +final class wire_cst_PaymentDetails_Bitcoin extends ffi.Struct { + external ffi.Pointer swap_id; + + external ffi.Pointer description; + + external ffi.Pointer refund_tx_id; + + external ffi.Pointer refund_tx_amount_sat; +} + +final class PaymentDetailsKind extends ffi.Union { + external wire_cst_PaymentDetails_Lightning Lightning; + + external wire_cst_PaymentDetails_Liquid Liquid; + + external wire_cst_PaymentDetails_Bitcoin Bitcoin; +} + +final class wire_cst_payment_details extends ffi.Struct { + @ffi.Int32() + external int tag; + + external PaymentDetailsKind kind; +} + +final class wire_cst_payment extends ffi.Struct { + external ffi.Pointer destination; + + external ffi.Pointer tx_id; + @ffi.Uint32() external int timestamp; @@ -1630,21 +1718,13 @@ final class wire_cst_payment extends ffi.Struct { @ffi.Uint64() external int fees_sat; - external ffi.Pointer preimage; - - external ffi.Pointer bolt11; - - external ffi.Pointer description; - - external ffi.Pointer refund_tx_id; - - external ffi.Pointer refund_tx_amount_sat; - @ffi.Int32() external int payment_type; @ffi.Int32() external int status; + + external ffi.Pointer details; } final class wire_cst_SdkEvent_PaymentFailed extends ffi.Struct { @@ -1759,89 +1839,6 @@ final class wire_cst_bitcoin_address_data extends ffi.Struct { external ffi.Pointer message; } -final class wire_cst_liquid_address_data extends ffi.Struct { - external ffi.Pointer address; - - @ffi.Int32() - external int network; - - external ffi.Pointer asset_id; - - external ffi.Pointer amount_sat; - - external ffi.Pointer label; - - external ffi.Pointer message; -} - -final class wire_cst_route_hint_hop extends ffi.Struct { - external ffi.Pointer src_node_id; - - @ffi.Uint64() - external int short_channel_id; - - @ffi.Uint32() - external int fees_base_msat; - - @ffi.Uint32() - external int fees_proportional_millionths; - - @ffi.Uint64() - external int cltv_expiry_delta; - - external ffi.Pointer htlc_minimum_msat; - - external ffi.Pointer htlc_maximum_msat; -} - -final class wire_cst_list_route_hint_hop extends ffi.Struct { - external ffi.Pointer ptr; - - @ffi.Int32() - external int len; -} - -final class wire_cst_route_hint extends ffi.Struct { - external ffi.Pointer hops; -} - -final class wire_cst_list_route_hint extends ffi.Struct { - external ffi.Pointer ptr; - - @ffi.Int32() - external int len; -} - -final class wire_cst_ln_invoice extends ffi.Struct { - external ffi.Pointer bolt11; - - @ffi.Int32() - external int network; - - external ffi.Pointer payee_pubkey; - - external ffi.Pointer payment_hash; - - external ffi.Pointer description; - - external ffi.Pointer description_hash; - - external ffi.Pointer amount_msat; - - @ffi.Uint64() - external int timestamp; - - @ffi.Uint64() - external int expiry; - - external ffi.Pointer routing_hints; - - external ffi.Pointer payment_secret; - - @ffi.Uint64() - external int min_final_cltv_expiry_delta; -} - final class wire_cst_ln_url_error_data extends ffi.Struct { external ffi.Pointer reason; } @@ -2329,6 +2326,14 @@ final class wire_cst_onchain_payment_limits_response extends ffi.Struct { external wire_cst_limits receive; } +final class wire_cst_PaymentError_AmountMissing extends ffi.Struct { + external ffi.Pointer err; +} + +final class wire_cst_PaymentError_InvalidNetwork extends ffi.Struct { + external ffi.Pointer err; +} + final class wire_cst_PaymentError_Generic extends ffi.Struct { external ffi.Pointer err; } @@ -2360,6 +2365,10 @@ final class wire_cst_PaymentError_SignerError extends ffi.Struct { } final class PaymentErrorKind extends ffi.Union { + external wire_cst_PaymentError_AmountMissing AmountMissing; + + external wire_cst_PaymentError_InvalidNetwork InvalidNetwork; + external wire_cst_PaymentError_Generic Generic; external wire_cst_PaymentError_InvalidInvoice InvalidInvoice; @@ -2392,16 +2401,8 @@ final class wire_cst_prepare_refund_response extends ffi.Struct { external ffi.Pointer refund_tx_id; } -final class wire_cst_receive_onchain_response extends ffi.Struct { - external ffi.Pointer address; - - external ffi.Pointer bip21; -} - final class wire_cst_receive_payment_response extends ffi.Struct { - external ffi.Pointer id; - - external ffi.Pointer invoice; + external ffi.Pointer destination; } final class wire_cst_recommended_fees extends ffi.Struct { diff --git a/packages/react-native/android/src/main/java/com/breezsdkliquid/BreezSDKLiquidMapper.kt b/packages/react-native/android/src/main/java/com/breezsdkliquid/BreezSDKLiquidMapper.kt index e2bb7b6..d161949 100644 --- a/packages/react-native/android/src/main/java/com/breezsdkliquid/BreezSDKLiquidMapper.kt +++ b/packages/react-native/android/src/main/java/com/breezsdkliquid/BreezSDKLiquidMapper.kt @@ -118,23 +118,23 @@ fun asBuyBitcoinRequest(buyBitcoinRequest: ReadableMap): BuyBitcoinRequest? { if (!validateMandatoryFields( buyBitcoinRequest, arrayOf( - "prepareRes", + "prepareResponse", ), ) ) { return null } - val prepareRes = buyBitcoinRequest.getMap("prepareRes")?.let { asPrepareBuyBitcoinResponse(it) }!! + val prepareResponse = buyBitcoinRequest.getMap("prepareResponse")?.let { asPrepareBuyBitcoinResponse(it) }!! val redirectUrl = if (hasNonNullKey(buyBitcoinRequest, "redirectUrl")) buyBitcoinRequest.getString("redirectUrl") else null return BuyBitcoinRequest( - prepareRes, + prepareResponse, redirectUrl, ) } fun readableMapOf(buyBitcoinRequest: BuyBitcoinRequest): ReadableMap = readableMapOf( - "prepareRes" to readableMapOf(buyBitcoinRequest.prepareRes), + "prepareResponse" to readableMapOf(buyBitcoinRequest.prepareResponse), "redirectUrl" to buyBitcoinRequest.redirectUrl, ) @@ -1213,24 +1213,24 @@ fun asPayOnchainRequest(payOnchainRequest: ReadableMap): PayOnchainRequest? { payOnchainRequest, arrayOf( "address", - "prepareRes", + "prepareResponse", ), ) ) { return null } val address = payOnchainRequest.getString("address")!! - val prepareRes = payOnchainRequest.getMap("prepareRes")?.let { asPreparePayOnchainResponse(it) }!! + val prepareResponse = payOnchainRequest.getMap("prepareResponse")?.let { asPreparePayOnchainResponse(it) }!! return PayOnchainRequest( address, - prepareRes, + prepareResponse, ) } fun readableMapOf(payOnchainRequest: PayOnchainRequest): ReadableMap = readableMapOf( "address" to payOnchainRequest.address, - "prepareRes" to readableMapOf(payOnchainRequest.prepareRes), + "prepareResponse" to readableMapOf(payOnchainRequest.prepareResponse), ) fun asPayOnchainRequestList(arr: ReadableArray): List { @@ -1253,54 +1253,41 @@ fun asPayment(payment: ReadableMap): Payment? { "feesSat", "paymentType", "status", - "description", ), ) ) { return null } + val destination = if (hasNonNullKey(payment, "destination")) payment.getString("destination") else null + val txId = if (hasNonNullKey(payment, "txId")) payment.getString("txId") else null val timestamp = payment.getInt("timestamp").toUInt() val amountSat = payment.getDouble("amountSat").toULong() val feesSat = payment.getDouble("feesSat").toULong() val paymentType = payment.getString("paymentType")?.let { asPaymentType(it) }!! val status = payment.getString("status")?.let { asPaymentState(it) }!! - val description = payment.getString("description")!! - val txId = if (hasNonNullKey(payment, "txId")) payment.getString("txId") else null - val swapId = if (hasNonNullKey(payment, "swapId")) payment.getString("swapId") else null - val preimage = if (hasNonNullKey(payment, "preimage")) payment.getString("preimage") else null - val bolt11 = if (hasNonNullKey(payment, "bolt11")) payment.getString("bolt11") else null - val refundTxId = if (hasNonNullKey(payment, "refundTxId")) payment.getString("refundTxId") else null - val refundTxAmountSat = if (hasNonNullKey(payment, "refundTxAmountSat")) payment.getDouble("refundTxAmountSat").toULong() else null + val details = if (hasNonNullKey(payment, "details")) payment.getMap("details")?.let { asPaymentDetails(it) } else null return Payment( + destination, + txId, timestamp, amountSat, feesSat, paymentType, status, - description, - txId, - swapId, - preimage, - bolt11, - refundTxId, - refundTxAmountSat, + details, ) } fun readableMapOf(payment: Payment): ReadableMap = readableMapOf( + "destination" to payment.destination, + "txId" to payment.txId, "timestamp" to payment.timestamp, "amountSat" to payment.amountSat, "feesSat" to payment.feesSat, "paymentType" to payment.paymentType.name.lowercase(), "status" to payment.status.name.lowercase(), - "description" to payment.description, - "txId" to payment.txId, - "swapId" to payment.swapId, - "preimage" to payment.preimage, - "bolt11" to payment.bolt11, - "refundTxId" to payment.refundTxId, - "refundTxAmountSat" to payment.refundTxAmountSat, + "details" to payment.details?.let { readableMapOf(it) }, ) fun asPaymentList(arr: ReadableArray): List { @@ -1474,136 +1461,92 @@ fun asPreparePayOnchainResponseList(arr: ReadableArray): List { - val list = ArrayList() +fun asPrepareReceiveRequestList(arr: ReadableArray): List { + val list = ArrayList() for (value in arr.toArrayList()) { when (value) { - is ReadableMap -> list.add(asPrepareReceiveOnchainRequest(value)!!) + is ReadableMap -> list.add(asPrepareReceiveRequest(value)!!) else -> throw SdkException.Generic(errUnexpectedType("${value::class.java.name}")) } } return list } -fun asPrepareReceiveOnchainResponse(prepareReceiveOnchainResponse: ReadableMap): PrepareReceiveOnchainResponse? { +fun asPrepareReceiveResponse(prepareReceiveResponse: ReadableMap): PrepareReceiveResponse? { if (!validateMandatoryFields( - prepareReceiveOnchainResponse, + prepareReceiveResponse, arrayOf( - "payerAmountSat", + "paymentMethod", "feesSat", ), ) ) { return null } - val payerAmountSat = prepareReceiveOnchainResponse.getDouble("payerAmountSat").toULong() - val feesSat = prepareReceiveOnchainResponse.getDouble("feesSat").toULong() - return PrepareReceiveOnchainResponse( + val payerAmountSat = + if (hasNonNullKey( + prepareReceiveResponse, + "payerAmountSat", + ) + ) { + prepareReceiveResponse.getDouble("payerAmountSat").toULong() + } else { + null + } + val paymentMethod = prepareReceiveResponse.getString("paymentMethod")?.let { asPaymentMethod(it) }!! + val feesSat = prepareReceiveResponse.getDouble("feesSat").toULong() + return PrepareReceiveResponse( payerAmountSat, + paymentMethod, feesSat, ) } -fun readableMapOf(prepareReceiveOnchainResponse: PrepareReceiveOnchainResponse): ReadableMap = +fun readableMapOf(prepareReceiveResponse: PrepareReceiveResponse): ReadableMap = readableMapOf( - "payerAmountSat" to prepareReceiveOnchainResponse.payerAmountSat, - "feesSat" to prepareReceiveOnchainResponse.feesSat, + "payerAmountSat" to prepareReceiveResponse.payerAmountSat, + "paymentMethod" to prepareReceiveResponse.paymentMethod.name.lowercase(), + "feesSat" to prepareReceiveResponse.feesSat, ) -fun asPrepareReceiveOnchainResponseList(arr: ReadableArray): List { - val list = ArrayList() +fun asPrepareReceiveResponseList(arr: ReadableArray): List { + val list = ArrayList() for (value in arr.toArrayList()) { when (value) { - is ReadableMap -> list.add(asPrepareReceiveOnchainResponse(value)!!) - else -> throw SdkException.Generic(errUnexpectedType("${value::class.java.name}")) - } - } - return list -} - -fun asPrepareReceivePaymentRequest(prepareReceivePaymentRequest: ReadableMap): PrepareReceivePaymentRequest? { - if (!validateMandatoryFields( - prepareReceivePaymentRequest, - arrayOf( - "payerAmountSat", - ), - ) - ) { - return null - } - val payerAmountSat = prepareReceivePaymentRequest.getDouble("payerAmountSat").toULong() - return PrepareReceivePaymentRequest( - payerAmountSat, - ) -} - -fun readableMapOf(prepareReceivePaymentRequest: PrepareReceivePaymentRequest): ReadableMap = - readableMapOf( - "payerAmountSat" to prepareReceivePaymentRequest.payerAmountSat, - ) - -fun asPrepareReceivePaymentRequestList(arr: ReadableArray): List { - val list = ArrayList() - for (value in arr.toArrayList()) { - when (value) { - is ReadableMap -> list.add(asPrepareReceivePaymentRequest(value)!!) - else -> throw SdkException.Generic(errUnexpectedType("${value::class.java.name}")) - } - } - return list -} - -fun asPrepareReceivePaymentResponse(prepareReceivePaymentResponse: ReadableMap): PrepareReceivePaymentResponse? { - if (!validateMandatoryFields( - prepareReceivePaymentResponse, - arrayOf( - "payerAmountSat", - "feesSat", - ), - ) - ) { - return null - } - val payerAmountSat = prepareReceivePaymentResponse.getDouble("payerAmountSat").toULong() - val feesSat = prepareReceivePaymentResponse.getDouble("feesSat").toULong() - return PrepareReceivePaymentResponse( - payerAmountSat, - feesSat, - ) -} - -fun readableMapOf(prepareReceivePaymentResponse: PrepareReceivePaymentResponse): ReadableMap = - readableMapOf( - "payerAmountSat" to prepareReceivePaymentResponse.payerAmountSat, - "feesSat" to prepareReceivePaymentResponse.feesSat, - ) - -fun asPrepareReceivePaymentResponseList(arr: ReadableArray): List { - val list = ArrayList() - for (value in arr.toArrayList()) { - when (value) { - is ReadableMap -> list.add(asPrepareReceivePaymentResponse(value)!!) + is ReadableMap -> list.add(asPrepareReceiveResponse(value)!!) else -> throw SdkException.Generic(errUnexpectedType("${value::class.java.name}")) } } @@ -1693,21 +1636,24 @@ fun asPrepareSendRequest(prepareSendRequest: ReadableMap): PrepareSendRequest? { if (!validateMandatoryFields( prepareSendRequest, arrayOf( - "invoice", + "destination", ), ) ) { return null } - val invoice = prepareSendRequest.getString("invoice")!! + val destination = prepareSendRequest.getString("destination")!! + val amountSat = if (hasNonNullKey(prepareSendRequest, "amountSat")) prepareSendRequest.getDouble("amountSat").toULong() else null return PrepareSendRequest( - invoice, + destination, + amountSat, ) } fun readableMapOf(prepareSendRequest: PrepareSendRequest): ReadableMap = readableMapOf( - "invoice" to prepareSendRequest.invoice, + "destination" to prepareSendRequest.destination, + "amountSat" to prepareSendRequest.amountSat, ) fun asPrepareSendRequestList(arr: ReadableArray): List { @@ -1725,24 +1671,24 @@ fun asPrepareSendResponse(prepareSendResponse: ReadableMap): PrepareSendResponse if (!validateMandatoryFields( prepareSendResponse, arrayOf( - "invoice", + "destination", "feesSat", ), ) ) { return null } - val invoice = prepareSendResponse.getString("invoice")!! + val destination = prepareSendResponse.getMap("destination")?.let { asSendDestination(it) }!! val feesSat = prepareSendResponse.getDouble("feesSat").toULong() return PrepareSendResponse( - invoice, + destination, feesSat, ) } fun readableMapOf(prepareSendResponse: PrepareSendResponse): ReadableMap = readableMapOf( - "invoice" to prepareSendResponse.invoice, + "destination" to readableMapOf(prepareSendResponse.destination), "feesSat" to prepareSendResponse.feesSat, ) @@ -1793,63 +1739,27 @@ fun asRateList(arr: ReadableArray): List { return list } -fun asReceiveOnchainResponse(receiveOnchainResponse: ReadableMap): ReceiveOnchainResponse? { - if (!validateMandatoryFields( - receiveOnchainResponse, - arrayOf( - "address", - "bip21", - ), - ) - ) { - return null - } - val address = receiveOnchainResponse.getString("address")!! - val bip21 = receiveOnchainResponse.getString("bip21")!! - return ReceiveOnchainResponse( - address, - bip21, - ) -} - -fun readableMapOf(receiveOnchainResponse: ReceiveOnchainResponse): ReadableMap = - readableMapOf( - "address" to receiveOnchainResponse.address, - "bip21" to receiveOnchainResponse.bip21, - ) - -fun asReceiveOnchainResponseList(arr: ReadableArray): List { - val list = ArrayList() - for (value in arr.toArrayList()) { - when (value) { - is ReadableMap -> list.add(asReceiveOnchainResponse(value)!!) - else -> throw SdkException.Generic(errUnexpectedType("${value::class.java.name}")) - } - } - return list -} - fun asReceivePaymentRequest(receivePaymentRequest: ReadableMap): ReceivePaymentRequest? { if (!validateMandatoryFields( receivePaymentRequest, arrayOf( - "prepareRes", + "prepareResponse", ), ) ) { return null } - val prepareRes = receivePaymentRequest.getMap("prepareRes")?.let { asPrepareReceivePaymentResponse(it) }!! + val prepareResponse = receivePaymentRequest.getMap("prepareResponse")?.let { asPrepareReceiveResponse(it) }!! val description = if (hasNonNullKey(receivePaymentRequest, "description")) receivePaymentRequest.getString("description") else null return ReceivePaymentRequest( - prepareRes, + prepareResponse, description, ) } fun readableMapOf(receivePaymentRequest: ReceivePaymentRequest): ReadableMap = readableMapOf( - "prepareRes" to readableMapOf(receivePaymentRequest.prepareRes), + "prepareResponse" to readableMapOf(receivePaymentRequest.prepareResponse), "description" to receivePaymentRequest.description, ) @@ -1868,25 +1778,21 @@ fun asReceivePaymentResponse(receivePaymentResponse: ReadableMap): ReceivePaymen if (!validateMandatoryFields( receivePaymentResponse, arrayOf( - "id", - "invoice", + "destination", ), ) ) { return null } - val id = receivePaymentResponse.getString("id")!! - val invoice = receivePaymentResponse.getString("invoice")!! + val destination = receivePaymentResponse.getString("destination")!! return ReceivePaymentResponse( - id, - invoice, + destination, ) } fun readableMapOf(receivePaymentResponse: ReceivePaymentResponse): ReadableMap = readableMapOf( - "id" to receivePaymentResponse.id, - "invoice" to receivePaymentResponse.invoice, + "destination" to receivePaymentResponse.destination, ) fun asReceivePaymentResponseList(arr: ReadableArray): List { @@ -2176,6 +2082,38 @@ fun asRouteHintHopList(arr: ReadableArray): List { return list } +fun asSendPaymentRequest(sendPaymentRequest: ReadableMap): SendPaymentRequest? { + if (!validateMandatoryFields( + sendPaymentRequest, + arrayOf( + "prepareResponse", + ), + ) + ) { + return null + } + val prepareResponse = sendPaymentRequest.getMap("prepareResponse")?.let { asPrepareSendResponse(it) }!! + return SendPaymentRequest( + prepareResponse, + ) +} + +fun readableMapOf(sendPaymentRequest: SendPaymentRequest): ReadableMap = + readableMapOf( + "prepareResponse" to readableMapOf(sendPaymentRequest.prepareResponse), + ) + +fun asSendPaymentRequestList(arr: ReadableArray): List { + val list = ArrayList() + for (value in arr.toArrayList()) { + when (value) { + is ReadableMap -> list.add(asSendPaymentRequest(value)!!) + else -> throw SdkException.Generic(errUnexpectedType("${value::class.java.name}")) + } + } + return list +} + fun asSendPaymentResponse(sendPaymentResponse: ReadableMap): SendPaymentResponse? { if (!validateMandatoryFields( sendPaymentResponse, @@ -2580,6 +2518,73 @@ fun asNetworkList(arr: ReadableArray): List { return list } +fun asPaymentDetails(paymentDetails: ReadableMap): PaymentDetails? { + val type = paymentDetails.getString("type") + + if (type == "lightning") { + return PaymentDetails.Lightning(paymentDetails.getString("swapId")!!) + } + if (type == "liquid") { + return PaymentDetails.Liquid(paymentDetails.getString("destination")!!) + } + if (type == "bitcoin") { + return PaymentDetails.Bitcoin(paymentDetails.getString("swapId")!!) + } + return null +} + +fun readableMapOf(paymentDetails: PaymentDetails): ReadableMap? { + val map = Arguments.createMap() + when (paymentDetails) { + is PaymentDetails.Lightning -> { + pushToMap(map, "type", "lightning") + pushToMap(map, "swapId", paymentDetails.swapId) + pushToMap(map, "description", paymentDetails.description) + pushToMap(map, "preimage", paymentDetails.preimage) + pushToMap(map, "bolt11", paymentDetails.bolt11) + pushToMap(map, "refundTxId", paymentDetails.refundTxId) + pushToMap(map, "refundTxAmountSat", paymentDetails.refundTxAmountSat) + } + is PaymentDetails.Liquid -> { + pushToMap(map, "type", "liquid") + pushToMap(map, "destination", paymentDetails.destination) + pushToMap(map, "description", paymentDetails.description) + } + is PaymentDetails.Bitcoin -> { + pushToMap(map, "type", "bitcoin") + pushToMap(map, "swapId", paymentDetails.swapId) + pushToMap(map, "description", paymentDetails.description) + pushToMap(map, "refundTxId", paymentDetails.refundTxId) + pushToMap(map, "refundTxAmountSat", paymentDetails.refundTxAmountSat) + } + } + return map +} + +fun asPaymentDetailsList(arr: ReadableArray): List { + val list = ArrayList() + for (value in arr.toArrayList()) { + when (value) { + is ReadableMap -> list.add(asPaymentDetails(value)!!) + else -> throw SdkException.Generic(errUnexpectedType("${value::class.java.name}")) + } + } + return list +} + +fun asPaymentMethod(type: String): PaymentMethod = PaymentMethod.valueOf(camelToUpperSnakeCase(type)) + +fun asPaymentMethodList(arr: ReadableArray): List { + val list = ArrayList() + for (value in arr.toArrayList()) { + when (value) { + is String -> list.add(asPaymentMethod(value)!!) + else -> throw SdkException.Generic(errUnexpectedType("${value::class.java.name}")) + } + } + return list +} + fun asPaymentState(type: String): PaymentState = PaymentState.valueOf(camelToUpperSnakeCase(type)) fun asPaymentStateList(arr: ReadableArray): List { @@ -2678,6 +2683,44 @@ fun asSdkEventList(arr: ReadableArray): List { return list } +fun asSendDestination(sendDestination: ReadableMap): SendDestination? { + val type = sendDestination.getString("type") + + if (type == "liquidAddress") { + return SendDestination.LiquidAddress(sendDestination.getMap("addressData")?.let { asLiquidAddressData(it) }!!) + } + if (type == "bolt11") { + return SendDestination.Bolt11(sendDestination.getMap("invoice")?.let { asLnInvoice(it) }!!) + } + return null +} + +fun readableMapOf(sendDestination: SendDestination): ReadableMap? { + val map = Arguments.createMap() + when (sendDestination) { + is SendDestination.LiquidAddress -> { + pushToMap(map, "type", "liquidAddress") + pushToMap(map, "addressData", readableMapOf(sendDestination.addressData)) + } + is SendDestination.Bolt11 -> { + pushToMap(map, "type", "bolt11") + pushToMap(map, "invoice", readableMapOf(sendDestination.invoice)) + } + } + return map +} + +fun asSendDestinationList(arr: ReadableArray): List { + val list = ArrayList() + for (value in arr.toArrayList()) { + when (value) { + is ReadableMap -> list.add(asSendDestination(value)!!) + else -> throw SdkException.Generic(errUnexpectedType("${value::class.java.name}")) + } + } + return list +} + fun asSuccessActionProcessed(successActionProcessed: ReadableMap): SuccessActionProcessed? { val type = successActionProcessed.getString("type") diff --git a/packages/react-native/android/src/main/java/com/breezsdkliquid/BreezSDKLiquidModule.kt b/packages/react-native/android/src/main/java/com/breezsdkliquid/BreezSDKLiquidModule.kt index 3552e1c..ee1a65b 100644 --- a/packages/react-native/android/src/main/java/com/breezsdkliquid/BreezSDKLiquidModule.kt +++ b/packages/react-native/android/src/main/java/com/breezsdkliquid/BreezSDKLiquidModule.kt @@ -210,9 +210,9 @@ class BreezSDKLiquidModule( ) { executor.execute { try { - val prepareSendResponse = - asPrepareSendResponse(req) ?: run { throw SdkException.Generic(errMissingMandatoryField("req", "PrepareSendResponse")) } - val res = getBindingLiquidSdk().sendPayment(prepareSendResponse) + val sendPaymentRequest = + asSendPaymentRequest(req) ?: run { throw SdkException.Generic(errMissingMandatoryField("req", "SendPaymentRequest")) } + val res = getBindingLiquidSdk().sendPayment(sendPaymentRequest) promise.resolve(readableMapOf(res)) } catch (e: Exception) { promise.reject(e.javaClass.simpleName.replace("Exception", "Error"), e.message, e) @@ -227,10 +227,10 @@ class BreezSDKLiquidModule( ) { executor.execute { try { - val prepareReceivePaymentRequest = - asPrepareReceivePaymentRequest(req) - ?: run { throw SdkException.Generic(errMissingMandatoryField("req", "PrepareReceivePaymentRequest")) } - val res = getBindingLiquidSdk().prepareReceivePayment(prepareReceivePaymentRequest) + val prepareReceiveRequest = + asPrepareReceiveRequest(req) + ?: run { throw SdkException.Generic(errMissingMandatoryField("req", "PrepareReceiveRequest")) } + val res = getBindingLiquidSdk().prepareReceivePayment(prepareReceiveRequest) promise.resolve(readableMapOf(res)) } catch (e: Exception) { promise.reject(e.javaClass.simpleName.replace("Exception", "Error"), e.message, e) @@ -315,42 +315,6 @@ class BreezSDKLiquidModule( } } - @ReactMethod - fun prepareReceiveOnchain( - req: ReadableMap, - promise: Promise, - ) { - executor.execute { - try { - val prepareReceiveOnchainRequest = - asPrepareReceiveOnchainRequest(req) - ?: run { throw SdkException.Generic(errMissingMandatoryField("req", "PrepareReceiveOnchainRequest")) } - val res = getBindingLiquidSdk().prepareReceiveOnchain(prepareReceiveOnchainRequest) - promise.resolve(readableMapOf(res)) - } catch (e: Exception) { - promise.reject(e.javaClass.simpleName.replace("Exception", "Error"), e.message, e) - } - } - } - - @ReactMethod - fun receiveOnchain( - req: ReadableMap, - promise: Promise, - ) { - executor.execute { - try { - val prepareReceiveOnchainResponse = - asPrepareReceiveOnchainResponse(req) - ?: run { throw SdkException.Generic(errMissingMandatoryField("req", "PrepareReceiveOnchainResponse")) } - val res = getBindingLiquidSdk().receiveOnchain(prepareReceiveOnchainResponse) - promise.resolve(readableMapOf(res)) - } catch (e: Exception) { - promise.reject(e.javaClass.simpleName.replace("Exception", "Error"), e.message, e) - } - } - } - @ReactMethod fun prepareBuyBitcoin( req: ReadableMap, diff --git a/packages/react-native/ios/BreezSDKLiquidMapper.swift b/packages/react-native/ios/BreezSDKLiquidMapper.swift index efd33dc..01f01ff 100644 --- a/packages/react-native/ios/BreezSDKLiquidMapper.swift +++ b/packages/react-native/ios/BreezSDKLiquidMapper.swift @@ -144,10 +144,10 @@ enum BreezSDKLiquidMapper { } static func asBuyBitcoinRequest(buyBitcoinRequest: [String: Any?]) throws -> BuyBitcoinRequest { - guard let prepareResTmp = buyBitcoinRequest["prepareRes"] as? [String: Any?] else { - throw SdkError.Generic(message: errMissingMandatoryField(fieldName: "prepareRes", typeName: "BuyBitcoinRequest")) + guard let prepareResponseTmp = buyBitcoinRequest["prepareResponse"] as? [String: Any?] else { + throw SdkError.Generic(message: errMissingMandatoryField(fieldName: "prepareResponse", typeName: "BuyBitcoinRequest")) } - let prepareRes = try asPrepareBuyBitcoinResponse(prepareBuyBitcoinResponse: prepareResTmp) + let prepareResponse = try asPrepareBuyBitcoinResponse(prepareBuyBitcoinResponse: prepareResponseTmp) var redirectUrl: String? if hasNonNilKey(data: buyBitcoinRequest, key: "redirectUrl") { @@ -158,14 +158,14 @@ enum BreezSDKLiquidMapper { } return BuyBitcoinRequest( - prepareRes: prepareRes, + prepareResponse: prepareResponse, redirectUrl: redirectUrl ) } static func dictionaryOf(buyBitcoinRequest: BuyBitcoinRequest) -> [String: Any?] { return [ - "prepareRes": dictionaryOf(prepareBuyBitcoinResponse: buyBitcoinRequest.prepareRes), + "prepareResponse": dictionaryOf(prepareBuyBitcoinResponse: buyBitcoinRequest.prepareResponse), "redirectUrl": buyBitcoinRequest.redirectUrl == nil ? nil : buyBitcoinRequest.redirectUrl, ] } @@ -1444,21 +1444,21 @@ enum BreezSDKLiquidMapper { guard let address = payOnchainRequest["address"] as? String else { throw SdkError.Generic(message: errMissingMandatoryField(fieldName: "address", typeName: "PayOnchainRequest")) } - guard let prepareResTmp = payOnchainRequest["prepareRes"] as? [String: Any?] else { - throw SdkError.Generic(message: errMissingMandatoryField(fieldName: "prepareRes", typeName: "PayOnchainRequest")) + guard let prepareResponseTmp = payOnchainRequest["prepareResponse"] as? [String: Any?] else { + throw SdkError.Generic(message: errMissingMandatoryField(fieldName: "prepareResponse", typeName: "PayOnchainRequest")) } - let prepareRes = try asPreparePayOnchainResponse(preparePayOnchainResponse: prepareResTmp) + let prepareResponse = try asPreparePayOnchainResponse(preparePayOnchainResponse: prepareResponseTmp) return PayOnchainRequest( address: address, - prepareRes: prepareRes + prepareResponse: prepareResponse ) } static func dictionaryOf(payOnchainRequest: PayOnchainRequest) -> [String: Any?] { return [ "address": payOnchainRequest.address, - "prepareRes": dictionaryOf(preparePayOnchainResponse: payOnchainRequest.prepareRes), + "prepareResponse": dictionaryOf(preparePayOnchainResponse: payOnchainRequest.prepareResponse), ] } @@ -1480,6 +1480,20 @@ enum BreezSDKLiquidMapper { } static func asPayment(payment: [String: Any?]) throws -> Payment { + var destination: String? + if hasNonNilKey(data: payment, key: "destination") { + guard let destinationTmp = payment["destination"] as? String else { + throw SdkError.Generic(message: errUnexpectedValue(fieldName: "destination")) + } + destination = destinationTmp + } + var txId: String? + if hasNonNilKey(data: payment, key: "txId") { + guard let txIdTmp = payment["txId"] as? String else { + throw SdkError.Generic(message: errUnexpectedValue(fieldName: "txId")) + } + txId = txIdTmp + } guard let timestamp = payment["timestamp"] as? UInt32 else { throw SdkError.Generic(message: errMissingMandatoryField(fieldName: "timestamp", typeName: "Payment")) } @@ -1499,82 +1513,33 @@ enum BreezSDKLiquidMapper { } let status = try asPaymentState(paymentState: statusTmp) - guard let description = payment["description"] as? String else { - throw SdkError.Generic(message: errMissingMandatoryField(fieldName: "description", typeName: "Payment")) - } - var txId: String? - if hasNonNilKey(data: payment, key: "txId") { - guard let txIdTmp = payment["txId"] as? String else { - throw SdkError.Generic(message: errUnexpectedValue(fieldName: "txId")) - } - txId = txIdTmp - } - var swapId: String? - if hasNonNilKey(data: payment, key: "swapId") { - guard let swapIdTmp = payment["swapId"] as? String else { - throw SdkError.Generic(message: errUnexpectedValue(fieldName: "swapId")) - } - swapId = swapIdTmp - } - var preimage: String? - if hasNonNilKey(data: payment, key: "preimage") { - guard let preimageTmp = payment["preimage"] as? String else { - throw SdkError.Generic(message: errUnexpectedValue(fieldName: "preimage")) - } - preimage = preimageTmp - } - var bolt11: String? - if hasNonNilKey(data: payment, key: "bolt11") { - guard let bolt11Tmp = payment["bolt11"] as? String else { - throw SdkError.Generic(message: errUnexpectedValue(fieldName: "bolt11")) - } - bolt11 = bolt11Tmp - } - var refundTxId: String? - if hasNonNilKey(data: payment, key: "refundTxId") { - guard let refundTxIdTmp = payment["refundTxId"] as? String else { - throw SdkError.Generic(message: errUnexpectedValue(fieldName: "refundTxId")) - } - refundTxId = refundTxIdTmp - } - var refundTxAmountSat: UInt64? - if hasNonNilKey(data: payment, key: "refundTxAmountSat") { - guard let refundTxAmountSatTmp = payment["refundTxAmountSat"] as? UInt64 else { - throw SdkError.Generic(message: errUnexpectedValue(fieldName: "refundTxAmountSat")) - } - refundTxAmountSat = refundTxAmountSatTmp + var details: PaymentDetails? + if let detailsTmp = payment["details"] as? [String: Any?] { + details = try asPaymentDetails(paymentDetails: detailsTmp) } return Payment( + destination: destination, + txId: txId, timestamp: timestamp, amountSat: amountSat, feesSat: feesSat, paymentType: paymentType, status: status, - description: description, - txId: txId, - swapId: swapId, - preimage: preimage, - bolt11: bolt11, - refundTxId: refundTxId, - refundTxAmountSat: refundTxAmountSat + details: details ) } static func dictionaryOf(payment: Payment) -> [String: Any?] { return [ + "destination": payment.destination == nil ? nil : payment.destination, + "txId": payment.txId == nil ? nil : payment.txId, "timestamp": payment.timestamp, "amountSat": payment.amountSat, "feesSat": payment.feesSat, "paymentType": valueOf(paymentType: payment.paymentType), "status": valueOf(paymentState: payment.status), - "description": payment.description, - "txId": payment.txId == nil ? nil : payment.txId, - "swapId": payment.swapId == nil ? nil : payment.swapId, - "preimage": payment.preimage == nil ? nil : payment.preimage, - "bolt11": payment.bolt11 == nil ? nil : payment.bolt11, - "refundTxId": payment.refundTxId == nil ? nil : payment.refundTxId, - "refundTxAmountSat": payment.refundTxAmountSat == nil ? nil : payment.refundTxAmountSat, + "details": payment.details == nil ? nil : dictionaryOf(paymentDetails: payment.details!), ] } @@ -1765,144 +1730,96 @@ enum BreezSDKLiquidMapper { return preparePayOnchainResponseList.map { v -> [String: Any?] in return dictionaryOf(preparePayOnchainResponse: v) } } - static func asPrepareReceiveOnchainRequest(prepareReceiveOnchainRequest: [String: Any?]) throws -> PrepareReceiveOnchainRequest { - guard let payerAmountSat = prepareReceiveOnchainRequest["payerAmountSat"] as? UInt64 else { - throw SdkError.Generic(message: errMissingMandatoryField(fieldName: "payerAmountSat", typeName: "PrepareReceiveOnchainRequest")) + static func asPrepareReceiveRequest(prepareReceiveRequest: [String: Any?]) throws -> PrepareReceiveRequest { + var payerAmountSat: UInt64? + if hasNonNilKey(data: prepareReceiveRequest, key: "payerAmountSat") { + guard let payerAmountSatTmp = prepareReceiveRequest["payerAmountSat"] as? UInt64 else { + throw SdkError.Generic(message: errUnexpectedValue(fieldName: "payerAmountSat")) + } + payerAmountSat = payerAmountSatTmp } + guard let paymentMethodTmp = prepareReceiveRequest["paymentMethod"] as? String else { + throw SdkError.Generic(message: errMissingMandatoryField(fieldName: "paymentMethod", typeName: "PrepareReceiveRequest")) + } + let paymentMethod = try asPaymentMethod(paymentMethod: paymentMethodTmp) - return PrepareReceiveOnchainRequest( - payerAmountSat: payerAmountSat) + return PrepareReceiveRequest( + payerAmountSat: payerAmountSat, + paymentMethod: paymentMethod + ) } - static func dictionaryOf(prepareReceiveOnchainRequest: PrepareReceiveOnchainRequest) -> [String: Any?] { + static func dictionaryOf(prepareReceiveRequest: PrepareReceiveRequest) -> [String: Any?] { return [ - "payerAmountSat": prepareReceiveOnchainRequest.payerAmountSat, + "payerAmountSat": prepareReceiveRequest.payerAmountSat == nil ? nil : prepareReceiveRequest.payerAmountSat, + "paymentMethod": valueOf(paymentMethod: prepareReceiveRequest.paymentMethod), ] } - static func asPrepareReceiveOnchainRequestList(arr: [Any]) throws -> [PrepareReceiveOnchainRequest] { - var list = [PrepareReceiveOnchainRequest]() + static func asPrepareReceiveRequestList(arr: [Any]) throws -> [PrepareReceiveRequest] { + var list = [PrepareReceiveRequest]() for value in arr { if let val = value as? [String: Any?] { - var prepareReceiveOnchainRequest = try asPrepareReceiveOnchainRequest(prepareReceiveOnchainRequest: val) - list.append(prepareReceiveOnchainRequest) + var prepareReceiveRequest = try asPrepareReceiveRequest(prepareReceiveRequest: val) + list.append(prepareReceiveRequest) } else { - throw SdkError.Generic(message: errUnexpectedType(typeName: "PrepareReceiveOnchainRequest")) + throw SdkError.Generic(message: errUnexpectedType(typeName: "PrepareReceiveRequest")) } } return list } - static func arrayOf(prepareReceiveOnchainRequestList: [PrepareReceiveOnchainRequest]) -> [Any] { - return prepareReceiveOnchainRequestList.map { v -> [String: Any?] in return dictionaryOf(prepareReceiveOnchainRequest: v) } + static func arrayOf(prepareReceiveRequestList: [PrepareReceiveRequest]) -> [Any] { + return prepareReceiveRequestList.map { v -> [String: Any?] in return dictionaryOf(prepareReceiveRequest: v) } } - static func asPrepareReceiveOnchainResponse(prepareReceiveOnchainResponse: [String: Any?]) throws -> PrepareReceiveOnchainResponse { - guard let payerAmountSat = prepareReceiveOnchainResponse["payerAmountSat"] as? UInt64 else { - throw SdkError.Generic(message: errMissingMandatoryField(fieldName: "payerAmountSat", typeName: "PrepareReceiveOnchainResponse")) + static func asPrepareReceiveResponse(prepareReceiveResponse: [String: Any?]) throws -> PrepareReceiveResponse { + var payerAmountSat: UInt64? + if hasNonNilKey(data: prepareReceiveResponse, key: "payerAmountSat") { + guard let payerAmountSatTmp = prepareReceiveResponse["payerAmountSat"] as? UInt64 else { + throw SdkError.Generic(message: errUnexpectedValue(fieldName: "payerAmountSat")) + } + payerAmountSat = payerAmountSatTmp } - guard let feesSat = prepareReceiveOnchainResponse["feesSat"] as? UInt64 else { - throw SdkError.Generic(message: errMissingMandatoryField(fieldName: "feesSat", typeName: "PrepareReceiveOnchainResponse")) + guard let paymentMethodTmp = prepareReceiveResponse["paymentMethod"] as? String else { + throw SdkError.Generic(message: errMissingMandatoryField(fieldName: "paymentMethod", typeName: "PrepareReceiveResponse")) + } + let paymentMethod = try asPaymentMethod(paymentMethod: paymentMethodTmp) + + guard let feesSat = prepareReceiveResponse["feesSat"] as? UInt64 else { + throw SdkError.Generic(message: errMissingMandatoryField(fieldName: "feesSat", typeName: "PrepareReceiveResponse")) } - return PrepareReceiveOnchainResponse( + return PrepareReceiveResponse( payerAmountSat: payerAmountSat, + paymentMethod: paymentMethod, feesSat: feesSat ) } - static func dictionaryOf(prepareReceiveOnchainResponse: PrepareReceiveOnchainResponse) -> [String: Any?] { + static func dictionaryOf(prepareReceiveResponse: PrepareReceiveResponse) -> [String: Any?] { return [ - "payerAmountSat": prepareReceiveOnchainResponse.payerAmountSat, - "feesSat": prepareReceiveOnchainResponse.feesSat, + "payerAmountSat": prepareReceiveResponse.payerAmountSat == nil ? nil : prepareReceiveResponse.payerAmountSat, + "paymentMethod": valueOf(paymentMethod: prepareReceiveResponse.paymentMethod), + "feesSat": prepareReceiveResponse.feesSat, ] } - static func asPrepareReceiveOnchainResponseList(arr: [Any]) throws -> [PrepareReceiveOnchainResponse] { - var list = [PrepareReceiveOnchainResponse]() + static func asPrepareReceiveResponseList(arr: [Any]) throws -> [PrepareReceiveResponse] { + var list = [PrepareReceiveResponse]() for value in arr { if let val = value as? [String: Any?] { - var prepareReceiveOnchainResponse = try asPrepareReceiveOnchainResponse(prepareReceiveOnchainResponse: val) - list.append(prepareReceiveOnchainResponse) + var prepareReceiveResponse = try asPrepareReceiveResponse(prepareReceiveResponse: val) + list.append(prepareReceiveResponse) } else { - throw SdkError.Generic(message: errUnexpectedType(typeName: "PrepareReceiveOnchainResponse")) + throw SdkError.Generic(message: errUnexpectedType(typeName: "PrepareReceiveResponse")) } } return list } - static func arrayOf(prepareReceiveOnchainResponseList: [PrepareReceiveOnchainResponse]) -> [Any] { - return prepareReceiveOnchainResponseList.map { v -> [String: Any?] in return dictionaryOf(prepareReceiveOnchainResponse: v) } - } - - static func asPrepareReceivePaymentRequest(prepareReceivePaymentRequest: [String: Any?]) throws -> PrepareReceivePaymentRequest { - guard let payerAmountSat = prepareReceivePaymentRequest["payerAmountSat"] as? UInt64 else { - throw SdkError.Generic(message: errMissingMandatoryField(fieldName: "payerAmountSat", typeName: "PrepareReceivePaymentRequest")) - } - - return PrepareReceivePaymentRequest( - payerAmountSat: payerAmountSat) - } - - static func dictionaryOf(prepareReceivePaymentRequest: PrepareReceivePaymentRequest) -> [String: Any?] { - return [ - "payerAmountSat": prepareReceivePaymentRequest.payerAmountSat, - ] - } - - static func asPrepareReceivePaymentRequestList(arr: [Any]) throws -> [PrepareReceivePaymentRequest] { - var list = [PrepareReceivePaymentRequest]() - for value in arr { - if let val = value as? [String: Any?] { - var prepareReceivePaymentRequest = try asPrepareReceivePaymentRequest(prepareReceivePaymentRequest: val) - list.append(prepareReceivePaymentRequest) - } else { - throw SdkError.Generic(message: errUnexpectedType(typeName: "PrepareReceivePaymentRequest")) - } - } - return list - } - - static func arrayOf(prepareReceivePaymentRequestList: [PrepareReceivePaymentRequest]) -> [Any] { - return prepareReceivePaymentRequestList.map { v -> [String: Any?] in return dictionaryOf(prepareReceivePaymentRequest: v) } - } - - static func asPrepareReceivePaymentResponse(prepareReceivePaymentResponse: [String: Any?]) throws -> PrepareReceivePaymentResponse { - guard let payerAmountSat = prepareReceivePaymentResponse["payerAmountSat"] as? UInt64 else { - throw SdkError.Generic(message: errMissingMandatoryField(fieldName: "payerAmountSat", typeName: "PrepareReceivePaymentResponse")) - } - guard let feesSat = prepareReceivePaymentResponse["feesSat"] as? UInt64 else { - throw SdkError.Generic(message: errMissingMandatoryField(fieldName: "feesSat", typeName: "PrepareReceivePaymentResponse")) - } - - return PrepareReceivePaymentResponse( - payerAmountSat: payerAmountSat, - feesSat: feesSat - ) - } - - static func dictionaryOf(prepareReceivePaymentResponse: PrepareReceivePaymentResponse) -> [String: Any?] { - return [ - "payerAmountSat": prepareReceivePaymentResponse.payerAmountSat, - "feesSat": prepareReceivePaymentResponse.feesSat, - ] - } - - static func asPrepareReceivePaymentResponseList(arr: [Any]) throws -> [PrepareReceivePaymentResponse] { - var list = [PrepareReceivePaymentResponse]() - for value in arr { - if let val = value as? [String: Any?] { - var prepareReceivePaymentResponse = try asPrepareReceivePaymentResponse(prepareReceivePaymentResponse: val) - list.append(prepareReceivePaymentResponse) - } else { - throw SdkError.Generic(message: errUnexpectedType(typeName: "PrepareReceivePaymentResponse")) - } - } - return list - } - - static func arrayOf(prepareReceivePaymentResponseList: [PrepareReceivePaymentResponse]) -> [Any] { - return prepareReceivePaymentResponseList.map { v -> [String: Any?] in return dictionaryOf(prepareReceivePaymentResponse: v) } + static func arrayOf(prepareReceiveResponseList: [PrepareReceiveResponse]) -> [Any] { + return prepareReceiveResponseList.map { v -> [String: Any?] in return dictionaryOf(prepareReceiveResponse: v) } } static func asPrepareRefundRequest(prepareRefundRequest: [String: Any?]) throws -> PrepareRefundRequest { @@ -1996,17 +1913,27 @@ enum BreezSDKLiquidMapper { } static func asPrepareSendRequest(prepareSendRequest: [String: Any?]) throws -> PrepareSendRequest { - guard let invoice = prepareSendRequest["invoice"] as? String else { - throw SdkError.Generic(message: errMissingMandatoryField(fieldName: "invoice", typeName: "PrepareSendRequest")) + guard let destination = prepareSendRequest["destination"] as? String else { + throw SdkError.Generic(message: errMissingMandatoryField(fieldName: "destination", typeName: "PrepareSendRequest")) + } + var amountSat: UInt64? + if hasNonNilKey(data: prepareSendRequest, key: "amountSat") { + guard let amountSatTmp = prepareSendRequest["amountSat"] as? UInt64 else { + throw SdkError.Generic(message: errUnexpectedValue(fieldName: "amountSat")) + } + amountSat = amountSatTmp } return PrepareSendRequest( - invoice: invoice) + destination: destination, + amountSat: amountSat + ) } static func dictionaryOf(prepareSendRequest: PrepareSendRequest) -> [String: Any?] { return [ - "invoice": prepareSendRequest.invoice, + "destination": prepareSendRequest.destination, + "amountSat": prepareSendRequest.amountSat == nil ? nil : prepareSendRequest.amountSat, ] } @@ -2028,22 +1955,24 @@ enum BreezSDKLiquidMapper { } static func asPrepareSendResponse(prepareSendResponse: [String: Any?]) throws -> PrepareSendResponse { - guard let invoice = prepareSendResponse["invoice"] as? String else { - throw SdkError.Generic(message: errMissingMandatoryField(fieldName: "invoice", typeName: "PrepareSendResponse")) + guard let destinationTmp = prepareSendResponse["destination"] as? [String: Any?] else { + throw SdkError.Generic(message: errMissingMandatoryField(fieldName: "destination", typeName: "PrepareSendResponse")) } + let destination = try asSendDestination(sendDestination: destinationTmp) + guard let feesSat = prepareSendResponse["feesSat"] as? UInt64 else { throw SdkError.Generic(message: errMissingMandatoryField(fieldName: "feesSat", typeName: "PrepareSendResponse")) } return PrepareSendResponse( - invoice: invoice, + destination: destination, feesSat: feesSat ) } static func dictionaryOf(prepareSendResponse: PrepareSendResponse) -> [String: Any?] { return [ - "invoice": prepareSendResponse.invoice, + "destination": dictionaryOf(sendDestination: prepareSendResponse.destination), "feesSat": prepareSendResponse.feesSat, ] } @@ -2103,49 +2032,11 @@ enum BreezSDKLiquidMapper { return rateList.map { v -> [String: Any?] in return dictionaryOf(rate: v) } } - static func asReceiveOnchainResponse(receiveOnchainResponse: [String: Any?]) throws -> ReceiveOnchainResponse { - guard let address = receiveOnchainResponse["address"] as? String else { - throw SdkError.Generic(message: errMissingMandatoryField(fieldName: "address", typeName: "ReceiveOnchainResponse")) - } - guard let bip21 = receiveOnchainResponse["bip21"] as? String else { - throw SdkError.Generic(message: errMissingMandatoryField(fieldName: "bip21", typeName: "ReceiveOnchainResponse")) - } - - return ReceiveOnchainResponse( - address: address, - bip21: bip21 - ) - } - - static func dictionaryOf(receiveOnchainResponse: ReceiveOnchainResponse) -> [String: Any?] { - return [ - "address": receiveOnchainResponse.address, - "bip21": receiveOnchainResponse.bip21, - ] - } - - static func asReceiveOnchainResponseList(arr: [Any]) throws -> [ReceiveOnchainResponse] { - var list = [ReceiveOnchainResponse]() - for value in arr { - if let val = value as? [String: Any?] { - var receiveOnchainResponse = try asReceiveOnchainResponse(receiveOnchainResponse: val) - list.append(receiveOnchainResponse) - } else { - throw SdkError.Generic(message: errUnexpectedType(typeName: "ReceiveOnchainResponse")) - } - } - return list - } - - static func arrayOf(receiveOnchainResponseList: [ReceiveOnchainResponse]) -> [Any] { - return receiveOnchainResponseList.map { v -> [String: Any?] in return dictionaryOf(receiveOnchainResponse: v) } - } - static func asReceivePaymentRequest(receivePaymentRequest: [String: Any?]) throws -> ReceivePaymentRequest { - guard let prepareResTmp = receivePaymentRequest["prepareRes"] as? [String: Any?] else { - throw SdkError.Generic(message: errMissingMandatoryField(fieldName: "prepareRes", typeName: "ReceivePaymentRequest")) + guard let prepareResponseTmp = receivePaymentRequest["prepareResponse"] as? [String: Any?] else { + throw SdkError.Generic(message: errMissingMandatoryField(fieldName: "prepareResponse", typeName: "ReceivePaymentRequest")) } - let prepareRes = try asPrepareReceivePaymentResponse(prepareReceivePaymentResponse: prepareResTmp) + let prepareResponse = try asPrepareReceiveResponse(prepareReceiveResponse: prepareResponseTmp) var description: String? if hasNonNilKey(data: receivePaymentRequest, key: "description") { @@ -2156,14 +2047,14 @@ enum BreezSDKLiquidMapper { } return ReceivePaymentRequest( - prepareRes: prepareRes, + prepareResponse: prepareResponse, description: description ) } static func dictionaryOf(receivePaymentRequest: ReceivePaymentRequest) -> [String: Any?] { return [ - "prepareRes": dictionaryOf(prepareReceivePaymentResponse: receivePaymentRequest.prepareRes), + "prepareResponse": dictionaryOf(prepareReceiveResponse: receivePaymentRequest.prepareResponse), "description": receivePaymentRequest.description == nil ? nil : receivePaymentRequest.description, ] } @@ -2186,23 +2077,17 @@ enum BreezSDKLiquidMapper { } static func asReceivePaymentResponse(receivePaymentResponse: [String: Any?]) throws -> ReceivePaymentResponse { - guard let id = receivePaymentResponse["id"] as? String else { - throw SdkError.Generic(message: errMissingMandatoryField(fieldName: "id", typeName: "ReceivePaymentResponse")) - } - guard let invoice = receivePaymentResponse["invoice"] as? String else { - throw SdkError.Generic(message: errMissingMandatoryField(fieldName: "invoice", typeName: "ReceivePaymentResponse")) + guard let destination = receivePaymentResponse["destination"] as? String else { + throw SdkError.Generic(message: errMissingMandatoryField(fieldName: "destination", typeName: "ReceivePaymentResponse")) } return ReceivePaymentResponse( - id: id, - invoice: invoice - ) + destination: destination) } static func dictionaryOf(receivePaymentResponse: ReceivePaymentResponse) -> [String: Any?] { return [ - "id": receivePaymentResponse.id, - "invoice": receivePaymentResponse.invoice, + "destination": receivePaymentResponse.destination, ] } @@ -2534,6 +2419,39 @@ enum BreezSDKLiquidMapper { return routeHintHopList.map { v -> [String: Any?] in return dictionaryOf(routeHintHop: v) } } + static func asSendPaymentRequest(sendPaymentRequest: [String: Any?]) throws -> SendPaymentRequest { + guard let prepareResponseTmp = sendPaymentRequest["prepareResponse"] as? [String: Any?] else { + throw SdkError.Generic(message: errMissingMandatoryField(fieldName: "prepareResponse", typeName: "SendPaymentRequest")) + } + let prepareResponse = try asPrepareSendResponse(prepareSendResponse: prepareResponseTmp) + + return SendPaymentRequest( + prepareResponse: prepareResponse) + } + + static func dictionaryOf(sendPaymentRequest: SendPaymentRequest) -> [String: Any?] { + return [ + "prepareResponse": dictionaryOf(prepareSendResponse: sendPaymentRequest.prepareResponse), + ] + } + + static func asSendPaymentRequestList(arr: [Any]) throws -> [SendPaymentRequest] { + var list = [SendPaymentRequest]() + for value in arr { + if let val = value as? [String: Any?] { + var sendPaymentRequest = try asSendPaymentRequest(sendPaymentRequest: val) + list.append(sendPaymentRequest) + } else { + throw SdkError.Generic(message: errUnexpectedType(typeName: "SendPaymentRequest")) + } + } + return list + } + + static func arrayOf(sendPaymentRequestList: [SendPaymentRequest]) -> [Any] { + return sendPaymentRequestList.map { v -> [String: Any?] in return dictionaryOf(sendPaymentRequest: v) } + } + static func asSendPaymentResponse(sendPaymentResponse: [String: Any?]) throws -> SendPaymentResponse { guard let paymentTmp = sendPaymentResponse["payment"] as? [String: Any?] else { throw SdkError.Generic(message: errMissingMandatoryField(fieldName: "payment", typeName: "SendPaymentResponse")) @@ -3222,6 +3140,129 @@ enum BreezSDKLiquidMapper { return list } + static func asPaymentDetails(paymentDetails: [String: Any?]) throws -> PaymentDetails { + let type = paymentDetails["type"] as! String + if type == "lightning" { + guard let _swapId = paymentDetails["swapId"] as? String else { + throw SdkError.Generic(message: errMissingMandatoryField(fieldName: "swapId", typeName: "PaymentDetails")) + } + return PaymentDetails.lightning(swapId: _swapId) + } + if type == "liquid" { + guard let _destination = paymentDetails["destination"] as? String else { + throw SdkError.Generic(message: errMissingMandatoryField(fieldName: "destination", typeName: "PaymentDetails")) + } + return PaymentDetails.liquid(destination: _destination) + } + if type == "bitcoin" { + guard let _swapId = paymentDetails["swapId"] as? String else { + throw SdkError.Generic(message: errMissingMandatoryField(fieldName: "swapId", typeName: "PaymentDetails")) + } + return PaymentDetails.bitcoin(swapId: _swapId) + } + + throw SdkError.Generic(message: "Unexpected type \(type) for enum PaymentDetails") + } + + static func dictionaryOf(paymentDetails: PaymentDetails) -> [String: Any?] { + switch paymentDetails { + case let .lightning( + swapId, description, preimage, bolt11, refundTxId, refundTxAmountSat + ): + return [ + "type": "lightning", + "swapId": swapId, + "description": description, + "preimage": preimage == nil ? nil : preimage, + "bolt11": bolt11 == nil ? nil : bolt11, + "refundTxId": refundTxId == nil ? nil : refundTxId, + "refundTxAmountSat": refundTxAmountSat == nil ? nil : refundTxAmountSat, + ] + + case let .liquid( + destination, description + ): + return [ + "type": "liquid", + "destination": destination, + "description": description, + ] + + case let .bitcoin( + swapId, description, refundTxId, refundTxAmountSat + ): + return [ + "type": "bitcoin", + "swapId": swapId, + "description": description, + "refundTxId": refundTxId == nil ? nil : refundTxId, + "refundTxAmountSat": refundTxAmountSat == nil ? nil : refundTxAmountSat, + ] + } + } + + static func arrayOf(paymentDetailsList: [PaymentDetails]) -> [Any] { + return paymentDetailsList.map { v -> [String: Any?] in return dictionaryOf(paymentDetails: v) } + } + + static func asPaymentDetailsList(arr: [Any]) throws -> [PaymentDetails] { + var list = [PaymentDetails]() + for value in arr { + if let val = value as? [String: Any?] { + var paymentDetails = try asPaymentDetails(paymentDetails: val) + list.append(paymentDetails) + } else { + throw SdkError.Generic(message: errUnexpectedType(typeName: "PaymentDetails")) + } + } + return list + } + + static func asPaymentMethod(paymentMethod: String) throws -> PaymentMethod { + switch paymentMethod { + case "lightning": + return PaymentMethod.lightning + + case "bitcoinAddress": + return PaymentMethod.bitcoinAddress + + case "liquidAddress": + return PaymentMethod.liquidAddress + + default: throw SdkError.Generic(message: "Invalid variant \(paymentMethod) for enum PaymentMethod") + } + } + + static func valueOf(paymentMethod: PaymentMethod) -> String { + switch paymentMethod { + case .lightning: + return "lightning" + + case .bitcoinAddress: + return "bitcoinAddress" + + case .liquidAddress: + return "liquidAddress" + } + } + + static func arrayOf(paymentMethodList: [PaymentMethod]) -> [String] { + return paymentMethodList.map { v -> String in return valueOf(paymentMethod: v) } + } + + static func asPaymentMethodList(arr: [Any]) throws -> [PaymentMethod] { + var list = [PaymentMethod]() + for value in arr { + if let val = value as? String { + var paymentMethod = try asPaymentMethod(paymentMethod: val) + list.append(paymentMethod) + } else { + throw SdkError.Generic(message: errUnexpectedType(typeName: "PaymentMethod")) + } + } + return list + } + static func asPaymentState(paymentState: String) throws -> PaymentState { switch paymentState { case "created": @@ -3461,6 +3502,65 @@ enum BreezSDKLiquidMapper { return list } + static func asSendDestination(sendDestination: [String: Any?]) throws -> SendDestination { + let type = sendDestination["type"] as! String + if type == "liquidAddress" { + guard let addressDataTmp = sendDestination["addressData"] as? [String: Any?] else { + throw SdkError.Generic(message: errMissingMandatoryField(fieldName: "addressData", typeName: "SendDestination")) + } + let _addressData = try asLiquidAddressData(liquidAddressData: addressDataTmp) + + return SendDestination.liquidAddress(addressData: _addressData) + } + if type == "bolt11" { + guard let invoiceTmp = sendDestination["invoice"] as? [String: Any?] else { + throw SdkError.Generic(message: errMissingMandatoryField(fieldName: "invoice", typeName: "SendDestination")) + } + let _invoice = try asLnInvoice(lnInvoice: invoiceTmp) + + return SendDestination.bolt11(invoice: _invoice) + } + + throw SdkError.Generic(message: "Unexpected type \(type) for enum SendDestination") + } + + static func dictionaryOf(sendDestination: SendDestination) -> [String: Any?] { + switch sendDestination { + case let .liquidAddress( + addressData + ): + return [ + "type": "liquidAddress", + "addressData": dictionaryOf(liquidAddressData: addressData), + ] + + case let .bolt11( + invoice + ): + return [ + "type": "bolt11", + "invoice": dictionaryOf(lnInvoice: invoice), + ] + } + } + + static func arrayOf(sendDestinationList: [SendDestination]) -> [Any] { + return sendDestinationList.map { v -> [String: Any?] in return dictionaryOf(sendDestination: v) } + } + + static func asSendDestinationList(arr: [Any]) throws -> [SendDestination] { + var list = [SendDestination]() + for value in arr { + if let val = value as? [String: Any?] { + var sendDestination = try asSendDestination(sendDestination: val) + list.append(sendDestination) + } else { + throw SdkError.Generic(message: errUnexpectedType(typeName: "SendDestination")) + } + } + return list + } + static func asSuccessActionProcessed(successActionProcessed: [String: Any?]) throws -> SuccessActionProcessed { let type = successActionProcessed["type"] as! String if type == "aes" { diff --git a/packages/react-native/ios/RNBreezSDKLiquid.m b/packages/react-native/ios/RNBreezSDKLiquid.m index 1cc0ecb..470a64f 100644 --- a/packages/react-native/ios/RNBreezSDKLiquid.m +++ b/packages/react-native/ios/RNBreezSDKLiquid.m @@ -94,18 +94,6 @@ RCT_EXTERN_METHOD( reject: (RCTPromiseRejectBlock)reject ) -RCT_EXTERN_METHOD( - prepareReceiveOnchain: (NSDictionary*)req - resolve: (RCTPromiseResolveBlock)resolve - reject: (RCTPromiseRejectBlock)reject -) - -RCT_EXTERN_METHOD( - receiveOnchain: (NSDictionary*)req - resolve: (RCTPromiseResolveBlock)resolve - reject: (RCTPromiseRejectBlock)reject -) - RCT_EXTERN_METHOD( prepareBuyBitcoin: (NSDictionary*)req resolve: (RCTPromiseResolveBlock)resolve diff --git a/packages/react-native/ios/RNBreezSDKLiquid.swift b/packages/react-native/ios/RNBreezSDKLiquid.swift index c0c46e0..81161c9 100644 --- a/packages/react-native/ios/RNBreezSDKLiquid.swift +++ b/packages/react-native/ios/RNBreezSDKLiquid.swift @@ -178,8 +178,8 @@ class RNBreezSDKLiquid: RCTEventEmitter { @objc(sendPayment:resolve:reject:) func sendPayment(_ req: [String: Any], resolve: @escaping RCTPromiseResolveBlock, reject: @escaping RCTPromiseRejectBlock) { do { - let prepareSendResponse = try BreezSDKLiquidMapper.asPrepareSendResponse(prepareSendResponse: req) - var res = try getBindingLiquidSdk().sendPayment(req: prepareSendResponse) + let sendPaymentRequest = try BreezSDKLiquidMapper.asSendPaymentRequest(sendPaymentRequest: req) + var res = try getBindingLiquidSdk().sendPayment(req: sendPaymentRequest) resolve(BreezSDKLiquidMapper.dictionaryOf(sendPaymentResponse: res)) } catch let err { rejectErr(err: err, reject: reject) @@ -189,9 +189,9 @@ class RNBreezSDKLiquid: RCTEventEmitter { @objc(prepareReceivePayment:resolve:reject:) func prepareReceivePayment(_ req: [String: Any], resolve: @escaping RCTPromiseResolveBlock, reject: @escaping RCTPromiseRejectBlock) { do { - let prepareReceivePaymentRequest = try BreezSDKLiquidMapper.asPrepareReceivePaymentRequest(prepareReceivePaymentRequest: req) - var res = try getBindingLiquidSdk().prepareReceivePayment(req: prepareReceivePaymentRequest) - resolve(BreezSDKLiquidMapper.dictionaryOf(prepareReceivePaymentResponse: res)) + let prepareReceiveRequest = try BreezSDKLiquidMapper.asPrepareReceiveRequest(prepareReceiveRequest: req) + var res = try getBindingLiquidSdk().prepareReceivePayment(req: prepareReceiveRequest) + resolve(BreezSDKLiquidMapper.dictionaryOf(prepareReceiveResponse: res)) } catch let err { rejectErr(err: err, reject: reject) } @@ -250,28 +250,6 @@ class RNBreezSDKLiquid: RCTEventEmitter { } } - @objc(prepareReceiveOnchain:resolve:reject:) - func prepareReceiveOnchain(_ req: [String: Any], resolve: @escaping RCTPromiseResolveBlock, reject: @escaping RCTPromiseRejectBlock) { - do { - let prepareReceiveOnchainRequest = try BreezSDKLiquidMapper.asPrepareReceiveOnchainRequest(prepareReceiveOnchainRequest: req) - var res = try getBindingLiquidSdk().prepareReceiveOnchain(req: prepareReceiveOnchainRequest) - resolve(BreezSDKLiquidMapper.dictionaryOf(prepareReceiveOnchainResponse: res)) - } catch let err { - rejectErr(err: err, reject: reject) - } - } - - @objc(receiveOnchain:resolve:reject:) - func receiveOnchain(_ req: [String: Any], resolve: @escaping RCTPromiseResolveBlock, reject: @escaping RCTPromiseRejectBlock) { - do { - let prepareReceiveOnchainResponse = try BreezSDKLiquidMapper.asPrepareReceiveOnchainResponse(prepareReceiveOnchainResponse: req) - var res = try getBindingLiquidSdk().receiveOnchain(req: prepareReceiveOnchainResponse) - resolve(BreezSDKLiquidMapper.dictionaryOf(receiveOnchainResponse: res)) - } catch let err { - rejectErr(err: err, reject: reject) - } - } - @objc(prepareBuyBitcoin:resolve:reject:) func prepareBuyBitcoin(_ req: [String: Any], resolve: @escaping RCTPromiseResolveBlock, reject: @escaping RCTPromiseRejectBlock) { do { diff --git a/packages/react-native/src/index.ts b/packages/react-native/src/index.ts index d9e9159..4ba14ac 100644 --- a/packages/react-native/src/index.ts +++ b/packages/react-native/src/index.ts @@ -37,7 +37,7 @@ export interface BitcoinAddressData { } export interface BuyBitcoinRequest { - prepareRes: PrepareBuyBitcoinResponse + prepareResponse: PrepareBuyBitcoinResponse redirectUrl?: string } @@ -208,22 +208,18 @@ export interface OnchainPaymentLimitsResponse { export interface PayOnchainRequest { address: string - prepareRes: PreparePayOnchainResponse + prepareResponse: PreparePayOnchainResponse } export interface Payment { + destination?: string + txId?: string timestamp: number amountSat: number feesSat: number paymentType: PaymentType status: PaymentState - description: string - txId?: string - swapId?: string - preimage?: string - bolt11?: string - refundTxId?: string - refundTxAmountSat?: number + details?: PaymentDetails } export interface PrepareBuyBitcoinRequest { @@ -248,21 +244,14 @@ export interface PreparePayOnchainResponse { totalFeesSat: number } -export interface PrepareReceiveOnchainRequest { - payerAmountSat: number +export interface PrepareReceiveRequest { + payerAmountSat?: number + paymentMethod: PaymentMethod } -export interface PrepareReceiveOnchainResponse { - payerAmountSat: number - feesSat: number -} - -export interface PrepareReceivePaymentRequest { - payerAmountSat: number -} - -export interface PrepareReceivePaymentResponse { - payerAmountSat: number +export interface PrepareReceiveResponse { + payerAmountSat?: number + paymentMethod: PaymentMethod feesSat: number } @@ -279,11 +268,12 @@ export interface PrepareRefundResponse { } export interface PrepareSendRequest { - invoice: string + destination: string + amountSat?: number } export interface PrepareSendResponse { - invoice: string + destination: SendDestination feesSat: number } @@ -292,19 +282,13 @@ export interface Rate { value: number } -export interface ReceiveOnchainResponse { - address: string - bip21: string -} - export interface ReceivePaymentRequest { - prepareRes: PrepareReceivePaymentResponse + prepareResponse: PrepareReceiveResponse description?: string } export interface ReceivePaymentResponse { - id: string - invoice: string + destination: string } export interface RecommendedFees { @@ -349,6 +333,10 @@ export interface RouteHintHop { htlcMaximumMsat?: number } +export interface SendPaymentRequest { + prepareResponse: PrepareSendResponse +} + export interface SendPaymentResponse { payment: Payment } @@ -482,6 +470,38 @@ export enum Network { REGTEST = "regtest" } +export enum PaymentDetailsVariant { + LIGHTNING = "lightning", + LIQUID = "liquid", + BITCOIN = "bitcoin" +} + +export type PaymentDetails = { + type: PaymentDetailsVariant.LIGHTNING, + swapId: string + description: string + preimage?: string + bolt11?: string + refundTxId?: string + refundTxAmountSat?: number +} | { + type: PaymentDetailsVariant.LIQUID, + destination: string + description: string +} | { + type: PaymentDetailsVariant.BITCOIN, + swapId: string + description: string + refundTxId?: string + refundTxAmountSat?: number +} + +export enum PaymentMethod { + LIGHTNING = "lightning", + BITCOIN_ADDRESS = "bitcoinAddress", + LIQUID_ADDRESS = "liquidAddress" +} + export enum PaymentState { CREATED = "created", PENDING = "pending", @@ -529,6 +549,19 @@ export type SdkEvent = { type: SdkEventVariant.SYNCED } +export enum SendDestinationVariant { + LIQUID_ADDRESS = "liquidAddress", + BOLT11 = "bolt11" +} + +export type SendDestination = { + type: SendDestinationVariant.LIQUID_ADDRESS, + addressData: LiquidAddressData +} | { + type: SendDestinationVariant.BOLT11, + invoice: LnInvoice +} + export enum SuccessActionProcessedVariant { AES = "aes", MESSAGE = "message", @@ -602,12 +635,12 @@ export const prepareSendPayment = async (req: PrepareSendRequest): Promise => { +export const sendPayment = async (req: SendPaymentRequest): Promise => { const response = await BreezSDKLiquid.sendPayment(req) return response } -export const prepareReceivePayment = async (req: PrepareReceivePaymentRequest): Promise => { +export const prepareReceivePayment = async (req: PrepareReceiveRequest): Promise => { const response = await BreezSDKLiquid.prepareReceivePayment(req) return response } @@ -637,16 +670,6 @@ export const payOnchain = async (req: PayOnchainRequest): Promise => { - const response = await BreezSDKLiquid.prepareReceiveOnchain(req) - return response -} - -export const receiveOnchain = async (req: PrepareReceiveOnchainResponse): Promise => { - const response = await BreezSDKLiquid.receiveOnchain(req) - return response -} - export const prepareBuyBitcoin = async (req: PrepareBuyBitcoinRequest): Promise => { const response = await BreezSDKLiquid.prepareBuyBitcoin(req) return response