diff --git a/lib/bindings/src/breez_sdk_liquid.udl b/lib/bindings/src/breez_sdk_liquid.udl index f2e05f47d..820bdfc89 100644 --- a/lib/bindings/src/breez_sdk_liquid.udl +++ b/lib/bindings/src/breez_sdk_liquid.udl @@ -1,7 +1,4 @@ -////////////////////////////////// -// BEGIN sdk-common mirror imports -// These are structs defined in sdk-common, which we want to make available in this project's UDL bindings - +/// Wrapper for a BOLT11 LN invoice dictionary LNInvoice { string bolt11; Network network; @@ -17,40 +14,82 @@ dictionary LNInvoice { u64 min_final_cltv_expiry_delta; }; +/// The different supported bitcoin networks enum Network { + /// Mainnet "Bitcoin", "Testnet", "Signet", "Regtest", }; +/// A route hint for a LN payment dictionary RouteHint { sequence hops; }; +/// Details of a specific hop in a larger route hint dictionary RouteHintHop { - string src_node_id; - string short_channel_id; - u32 fees_base_msat; - u32 fees_proportional_millionths; - u64 cltv_expiry_delta; - u64? htlc_minimum_msat; - u64? htlc_maximum_msat; -}; - + /// The node id of the non-target end of the route + string src_node_id; + /// The short channel id of this channel + string short_channel_id; + /// The fees which must be paid to use this channel + u32 fees_base_msat; + u32 fees_proportional_millionths; + /// The difference in CLTV values between this node and the next node + u64 cltv_expiry_delta; + /// The minimum value, in msat, which must be relayed to the next hop + u64? htlc_minimum_msat; + /// The maximum value in msat available for routing with a single HTLC + u64? htlc_maximum_msat; +}; + +/// Different kinds of inputs supported by [parse], including any relevant details extracted from the input [Enum] interface InputType { + /// # Supported standards + /// + /// - plain on-chain BTC address + /// - BIP21 BitcoinAddress(BitcoinAddressData address); + /// # Supported standards + /// + /// - plain on-chain liquid address + /// - BIP21 on liquid/liquidtestnet LiquidAddress(LiquidAddressData address); Bolt11(LNInvoice invoice); NodeId(string node_id); Url(string url); + /// # Supported standards + /// + /// - LUD-01 LNURL bech32 encoding + /// - LUD-06 `payRequest` spec + /// - LUD-16 LN Address + /// - LUD-17 Support for lnurlp prefix with non-bech32-encoded LNURL URLs LnUrlPay(LnUrlPayRequestData data); + /// # Supported standards + /// + /// - LUD-01 LNURL bech32 encoding + /// - LUD-03 `withdrawRequest` spec + /// - LUD-17 Support for lnurlw prefix with non-bech32-encoded LNURL URLs + /// + /// # Not supported (yet) + /// + /// - LUD-14 `balanceCheck`: reusable `withdrawRequest`s + /// - LUD-19 Pay link discoverable from withdraw link LnUrlWithdraw(LnUrlWithdrawRequestData data); + /// # Supported standards + /// + /// - LUD-01 LNURL bech32 encoding + /// - LUD-04 `auth` base spec + /// - LUD-17 Support for keyauth prefix with non-bech32-encoded LNURL URLs LnUrlAuth(LnUrlAuthRequestData data); + /// Error returned by the LNURL endpoint LnUrlError(LnUrlErrorData data); }; +/// Wrapped in a [InputType::BitcoinAddress], this is the result of [parse] when given a plain or BIP-21 BTC address. dictionary BitcoinAddressData { string address; Network network; @@ -59,6 +98,7 @@ dictionary BitcoinAddressData { string? message; }; +/// Wrapped in a [InputType::LiquidAddress], this is the result of [parse] when given a plain or BIP-21 Liquid address. dictionary LiquidAddressData { string address; Network network; @@ -68,33 +108,76 @@ dictionary LiquidAddressData { string? message; }; +/// Wrapped in a [InputType::LnUrlPay], this is the result of [parse] when given a LNURL-pay endpoint. +/// +/// It represents the endpoint's parameters for the LNURL workflow. +/// +/// See dictionary LnUrlPayRequestData { string callback; + /// The minimum amount, in millisats, that this LNURL-pay endpoint accepts u64 min_sendable; + /// The maximum amount, in millisats, that this LNURL-pay endpoint accepts u64 max_sendable; + /// As per LUD-06, `metadata` is a raw string (e.g. a json representation of the inner map) string metadata_str; + /// The comment length accepted by this endpoint + /// + /// See u16 comment_allowed; + /// Indicates the domain of the LNURL-pay service, to be shown to the user when asking for + /// payment input, as per LUD-06 spec. + /// + /// Note: this is not the domain of the callback, but the domain of the LNURL-pay endpoint. string domain; + /// Value indicating whether the recipient supports Nostr Zaps through NIP-57. + /// + /// See boolean allows_nostr; + /// Optional recipient's lnurl provider's Nostr pubkey for NIP-57. If it exists it should be a + /// valid BIP 340 public key in hex. + /// + /// See + /// See string? nostr_pubkey; + /// If sending to a LN Address, this will be filled. string? ln_address; }; +/// Wrapped in a [InputType::LnUrlWithdraw], this is the result of [parse] when given a LNURL-withdraw endpoint. +/// +/// It represents the endpoint's parameters for the LNURL workflow. +/// +/// See dictionary LnUrlWithdrawRequestData { string callback; string k1; string default_description; + /// The minimum amount, in millisats, that this LNURL-withdraw endpoint accepts u64 min_withdrawable; + /// The maximum amount, in millisats, that this LNURL-withdraw endpoint accepts u64 max_withdrawable; }; +/// Wrapped in a [InputType::LnUrlAuth], this is the result of [parse] when given a LNURL-auth endpoint. +/// +/// It represents the endpoint's parameters for the LNURL workflow. +/// +/// See dictionary LnUrlAuthRequestData { + /// Hex encoded 32 bytes of challenge string k1; + /// Indicates the domain of the LNURL-auth service, to be shown to the user when asking for + /// auth confirmation, as per LUD-04 spec. string domain; + /// Indicates the URL of the LNURL-auth service, including the query arguments. This will be + /// extended with the signed challenge and the linking key, then called in the second step of the workflow. string url; + /// When available, one of: register, login, link, auth string? action = null; }; +/// Wrapped in a [InputType::LnUrlError], this represents a LNURL-endpoint error. dictionary LnUrlErrorData { string reason; }; @@ -106,24 +189,35 @@ interface SuccessActionProcessed { Url(UrlSuccessActionData data); }; +/// Result of decryption of [SuccessActionProcessed::Aes] payload [Enum] interface AesSuccessActionDataResult { Decrypted(AesSuccessActionDataDecrypted data); ErrorStatus(string reason); }; +/// Wrapper for the decrypted [AesSuccessActionDataResult::Decrypted] payload dictionary AesSuccessActionDataDecrypted { + /// Contents description, up to 144 characters string description; + /// Decrypted content string plaintext; }; +/// Wrapper for the [SuccessActionProcessed::Message] payload dictionary MessageSuccessActionData { string message; }; +/// Wrapper for the [SuccessActionProcessed::Url] payload dictionary UrlSuccessActionData { + /// Contents description, up to 144 characters string description; + /// URL of the success action string url; + /// Indicates the success URL domain matches the LNURL callback domain. + /// + /// See boolean matches_callback_domain; }; @@ -132,40 +226,74 @@ dictionary LnUrlPayErrorData { string reason; }; +/// Represents a LNURL-pay request. dictionary LnUrlPayRequest { + /// The [LnUrlPayRequestData] returned by [parse] LnUrlPayRequestData data; + /// The amount in millisatoshis for this payment u64 amount_msat; + /// An optional comment for this payment string? comment = null; + /// The external label or identifier of the [Payment] string? payment_label = null; + /// Validates that, if there is a URL success action, the URL domain matches + /// the LNURL callback domain. Defaults to `true` boolean? validate_success_action_url = null; }; +/// Error returned by [BindingLiquidSdk::lnurl_pay] [Error] interface LnUrlPayError { + /// This error is raised when attempting to pay an invoice that has already being paid. AlreadyPaid(); + /// This error is raised when a general error occurs not specific to other error variants + /// in this enum. Generic(string err); + /// This error is raised when the amount from the parsed invoice is not set. InvalidAmount(string err); + /// This error is raised when the lightning invoice cannot be parsed. InvalidInvoice(string err); + /// This error is raised when the lightning invoice is for a different Bitcoin network. InvalidNetwork(string err); + /// This error is raised when the decoded LNURL URI is not compliant to the specification. InvalidUri(string err); + /// This error is raised when the lightning invoice has passed it's expiry time. InvoiceExpired(string err); + /// This error is raised when attempting to make a payment by the node fails. PaymentFailed(string err); + /// This error is raised when attempting to make a payment takes too long. PaymentTimeout(string err); + /// This error is raised when no route can be found when attempting to make a + /// payment by the node. RouteNotFound(string err); + /// This error is raised when the route is considered too expensive when + /// attempting to make a payment by the node. RouteTooExpensive(string err); + /// This error is raised when a connection to an external service fails. ServiceConnectivity(string err); }; +/// Error returned by [BindingLiquidSdk::lnurl_withdraw] [Error] interface LnUrlWithdrawError { + /// This error is raised when a general error occurs not specific to other error variants + /// in this enum. Generic(string err); + /// This error is raised when the amount is zero or the amount does not cover + /// the cost to open a new channel. InvalidAmount(string err); + /// This error is raised when the lightning invoice cannot be parsed. InvalidInvoice(string err); + /// This error is raised when the decoded LNURL URI is not compliant to the specification. InvalidUri(string err); - ServiceConnectivity(string err); + /// This error is raised when no routing hints were able to be added to the invoice + /// while trying to receive a payment. InvoiceNoRoutingHints(string err); + /// This error is raised when a connection to an external service fails. + ServiceConnectivity(string err); }; +/// [LnUrlCallbackStatus] specific to LNURL-withdraw, where the success case contains the invoice. [Enum] interface LnUrlWithdrawResult { Ok(LnUrlWithdrawSuccessData data); @@ -177,33 +305,47 @@ dictionary LnUrlWithdrawSuccessData { LNInvoice invoice; }; -dictionary LnUrlWithdrawRequestData { - string callback; - string k1; - string default_description; - u64 min_withdrawable; - u64 max_withdrawable; -}; - dictionary LnUrlWithdrawRequest { + /// Request data containing information on how to call the lnurl withdraw + /// endpoint. Typically retrieved by calling [parse] on a lnurl withdraw + /// input. LnUrlWithdrawRequestData data; + /// The amount to withdraw from the lnurl withdraw endpoint. Must be between + /// `min_withdrawable` and `max_withdrawable`. u64 amount_msat; + /// Optional description that will be put in the payment request for the + /// lnurl withdraw endpoint. string? description = null; }; +/// Contains the result of the entire LNURL interaction, as reported by the LNURL endpoint. +/// +/// * [LnUrlCallbackStatus::Ok] indicates the interaction with the endpoint was valid, and the endpoint +/// - started to pay the invoice asynchronously in the case of LNURL-withdraw, +/// - verified the client signature in the case of LNURL-auth +/// * [LnUrlCallbackStatus::ErrorStatus] indicates a generic issue the LNURL endpoint encountered, including a freetext +/// description of the reason. +/// +/// Both cases are described in LUD-03 & LUD-04: [Enum] interface LnUrlCallbackStatus { Ok(); ErrorStatus(LnUrlErrorData data); }; +/// Error returned by [BindingLiquidSdk::lnurl_auth] [Error] interface LnUrlAuthError { + /// This error is raised when a general error occurs not specific to other error variants + /// in this enum. Generic(string err); + /// This error is raised when the decoded LNURL URI is not compliant to the specification. InvalidUri(string err); + /// This error is raised when a connection to an external service fails. ServiceConnectivity(string err); }; +/// Denominator in an exchange rate dictionary Rate { string coin; f64 value; @@ -214,6 +356,7 @@ dictionary FiatCurrency { CurrencyInfo info; }; +/// Settings for the symbol representation of a currency dictionary Symbol { string? grapheme; string? template; @@ -221,17 +364,20 @@ dictionary Symbol { u32? position; }; +/// Locale-specific settings for the representation of a currency dictionary LocaleOverrides { string locale; u32? spacing; Symbol symbol; }; +/// Localized name of a currency dictionary LocalizedName { string locale; string name; }; +/// Details about a supported currency in the fiat rate feed dictionary CurrencyInfo { string name; u32 fraction_size; @@ -242,13 +388,21 @@ dictionary CurrencyInfo { sequence locale_overrides; }; -// END sdk-common mirror imports -//////////////////////////////// - -////////////////////////////////// +// -------------------------------------------------------- // BEGIN sdk-common wrappers // These are connecting structures that glue relevant sdk-common structs to the SDK +/// Contains the result of the entire LNURL-pay interaction, as reported by the LNURL endpoint. +/// +/// * [LnUrlPayResult::EndpointSuccess] indicates the payment is complete. The endpoint may return a [SuccessActionProcessed], +/// in which case, the wallet has to present it to the user as described in +/// +/// +/// * [LnUrlPayResult::EndpointError] indicates a generic issue the LNURL endpoint encountered, including a freetext +/// field with the reason. +/// +/// * [LnUrlPayResult::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. [Enum] interface LnUrlPayResult { EndpointSuccess(LnUrlPaySuccessData data); @@ -262,7 +416,7 @@ dictionary LnUrlPaySuccessData { }; // END sdk-common wrappers -//////////////////////////////// +// -------------------------------------------------------- [Error] enum SdkError { @@ -297,192 +451,305 @@ enum PaymentError { "SignerError", }; +/// Configuration for the Liquid SDK dictionary Config { string liquid_electrum_url; string bitcoin_electrum_url; + /// The mempool.space API URL, has to be in the format: https://mempool.space/api string mempoolspace_url; + /// Directory in which all SDK files (DB, log, cache) are stored. + /// + /// Prefix can be a relative or absolute path to this directory. string working_dir; LiquidNetwork network; + /// Send payment timeout. See [BindingLiquidSdk::send_payment] u64 payment_timeout_sec; + /// Zero-conf minimum accepted fee-rate in millisatoshis per vbyte u32 zero_conf_min_fee_rate_msat; + /// Maximum amount in satoshi to accept zero-conf payments with + /// Defaults to [crate::receive_swap::DEFAULT_ZERO_CONF_MAX_SAT] u64? zero_conf_max_amount_sat; + /// The Breez API key used for making requests to their mempool service string? breez_api_key; }; +/// Network chosen for this Liquid SDK instance. Note that it represents both the Liquid and the +/// Bitcoin network used. enum LiquidNetwork { + /// Mainnet Bitcoin and Liquid chains "Mainnet", + /// Testnet Bitcoin and Liquid chains "Testnet", }; +/// An argument when calling [BindingLiquidSdk::connect]. dictionary ConnectRequest { Config config; string mnemonic; }; +/// Returned when calling [BindingLiquidSdk::get_info]. dictionary GetInfoResponse { + /// Usable balance. This is the confirmed onchain balance minus `pending_send_sat`. u64 balance_sat; + /// Amount that is being used for ongoing Send swaps u64 pending_send_sat; + /// Incoming amount that is pending from ongoing Receive swaps u64 pending_receive_sat; string pubkey; }; +/// An argument when calling [BindingLiquidSdk::sign_message]. dictionary SignMessageRequest { string message; }; +/// Returned when calling [BindingLiquidSdk::sign_message]. dictionary SignMessageResponse { string signature; }; +/// An argument when calling [BindingLiquidSdk::check_message]. dictionary CheckMessageRequest { + /// The message that was signed. string message; + /// The public key of the node that signed the message. string pubkey; + /// The zbase encoded signature to verify. string signature; }; +/// Returned when calling [BindingLiquidSdk::check_message]. dictionary CheckMessageResponse { + /// Boolean value indicating whether the signature covers the message and + /// was signed by the given pubkey. boolean is_valid; }; +/// An argument when calling [BindingLiquidSdk::prepare_send_payment]. dictionary PrepareSendRequest { + /// The destination we intend to pay to. + /// Supports BIP21 URIs, BOLT11 invoices and Liquid addresses string destination; + /// Should only be set when paying directly onchain or to a BIP21 URI + /// where no amount is specified u64? amount_sat = null; }; +/// Specifies the supported destinations which can be payed by the SDK [Enum] interface SendDestination { LiquidAddress(LiquidAddressData address_data); Bolt11(LNInvoice invoice); }; +/// Returned when calling [BindingLiquidSdk::prepare_send_payment]. dictionary PrepareSendResponse { SendDestination destination; u64 fees_sat; }; +/// An argument when calling [BindingLiquidSdk::send_payment]. dictionary SendPaymentRequest { PrepareSendResponse prepare_response; }; +/// Returned when calling [BindingLiquidSdk::send_payment]. dictionary SendPaymentResponse { Payment payment; }; +/// The send/receive methods supported by the SDK enum PaymentMethod { "Lightning", "BitcoinAddress", "LiquidAddress", }; +/// An argument when calling [BindingLiquidSdk::prepare_receive_payment]. dictionary PrepareReceiveRequest { PaymentMethod payment_method; u64? payer_amount_sat = null; }; +/// Returned when calling [BindingLiquidSdk::prepare_receive_payment]. dictionary PrepareReceiveResponse { u64? payer_amount_sat; PaymentMethod payment_method; u64 fees_sat; }; +/// An argument when calling [BindingLiquidSdk::receive_payment]. dictionary ReceivePaymentRequest { PrepareReceiveResponse prepare_response; + /// The description for this payment request. string? description = null; + /// If set to true, then the hash of the description will be used. boolean? use_description_hash = null; }; +/// Returned when calling [BindingLiquidSdk::receive_payment]. dictionary ReceivePaymentResponse { + /// Either a BIP21 URI (Liquid or Bitcoin), a Liquid address + /// or an invoice, depending on the [PrepareReceiveResponse] parameters string destination; }; +/// The minimum and maximum in satoshis of a Lightning or onchain payment. dictionary Limits { u64 min_sat; u64 max_sat; u64 max_zero_conf_sat; }; +/// Returned when calling [BindingLiquidSdk::fetch_lightning_limits]. dictionary LightningPaymentLimitsResponse { + /// Amount limits for a Send Payment to be valid Limits send; + /// Amount limits for a Receive Payment to be valid Limits receive; }; +/// Returned when calling [BindingLiquidSdk::fetch_onchain_limits]. dictionary OnchainPaymentLimitsResponse { + /// Amount limits for a Send Onchain Payment to be valid Limits send; + /// Amount limits for a Receive Onchain Payment to be valid Limits receive; }; [Enum] interface PayOnchainAmount { + /// The amount in satoshi that will be received Receiver(u64 amount_sat); + /// Indicates that all available funds should be sent Drain(); }; +/// An argument when calling [BindingLiquidSdk::prepare_pay_onchain]. dictionary PreparePayOnchainRequest { PayOnchainAmount amount; + /// The optional fee rate of the Bitcoin claim transaction in sat/vB. Defaults to the swapper estimated claim fee. u32? fee_rate_sat_per_vbyte = null; }; +/// Returned when calling [BindingLiquidSdk::prepare_pay_onchain]. dictionary PreparePayOnchainResponse { u64 receiver_amount_sat; u64 claim_fees_sat; u64 total_fees_sat; }; +/// An argument when calling [BindingLiquidSdk::pay_onchain]. dictionary PayOnchainRequest { string address; PreparePayOnchainResponse prepare_response; }; +/// An argument of [PrepareBuyBitcoinRequest] when calling [BindingLiquidSdk::prepare_buy_bitcoin]. enum BuyBitcoinProvider { "Moonpay", }; +/// An argument when calling [BindingLiquidSdk::prepare_buy_bitcoin]. dictionary PrepareBuyBitcoinRequest { BuyBitcoinProvider provider; u64 amount_sat; }; +/// Returned when calling [BindingLiquidSdk::prepare_buy_bitcoin]. dictionary PrepareBuyBitcoinResponse { BuyBitcoinProvider provider; u64 amount_sat; u64 fees_sat; }; +/// An argument when calling [BindingLiquidSdk::buy_bitcoin]. dictionary BuyBitcoinRequest { PrepareBuyBitcoinResponse prepare_response; + /// The optional URL to redirect to after completing the buy. + /// + /// For Moonpay, see string? redirect_url = null; }; +/// An argument when calling [BindingLiquidSdk::backup]. dictionary BackupRequest { + /// Path to the backup. + /// + /// If not set, it defaults to 'backup.sql' for mainnet and 'backup-testnet.sql' for testnet. + /// The file will be saved in [ConnectRequest]'s `data_dir`. string? backup_path = null; }; +/// An argument when calling [BindingLiquidSdk::restore]. dictionary RestoreRequest { string? backup_path = null; }; +/// An argument when calling [BindingLiquidSdk::list_payments]. dictionary ListPaymentsRequest { sequence? filters = null; + /// Epoch time, in seconds i64? from_timestamp = null; + /// Epoch time, in seconds i64? to_timestamp = null; u32? offset = null; u32? limit = null; }; +/// The specific details of a payment, depending on its type [Enum] interface PaymentDetails { + /// Swapping to or from Lightning Lightning(string swap_id, string description, string? preimage, string? bolt11, string? refund_tx_id, u64? refund_tx_amount_sat); + /// Direct onchain payment to a Liquid address Liquid(string destination, string description); + /// Swapping to or from the Bitcoin chain Bitcoin(string swap_id, string description, string? refund_tx_id, u64? refund_tx_amount_sat); }; +/// Represents an SDK payment. +/// +/// By default, this is an onchain tx. It may represent a swap, if swap metadata is available. dictionary Payment { + /// 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 + /// in time when the underlying tx was included in a block. If there is no associated swap + /// available and the underlying tx is not yet confirmed, the value is 'now()'. u32 timestamp; + /// The payment amount, which corresponds to the onchain tx amount. + /// + /// In case of an outbound payment (Send), this is the payer amount. Otherwise it's the receiver amount. u64 amount_sat; + /// Represents the fees paid by this wallet for this payment. + /// + /// ### Swaps + /// If there is an associated Send Swap, these fees represent the total fees paid by this wallet + /// (the sender). It is the difference between the amount that was sent and the amount received. + /// + /// If there is an associated Receive Swap, these fees represent the total fees paid by this wallet + /// (the receiver). It is also the difference between the amount that was sent and the amount received. + /// + /// ### Pure onchain txs + /// If no swap is associated with this payment: + /// - for Send payments, this is the onchain tx fee + /// - for Receive payments, this is zero u64 fees_sat; + /// If it is a [PaymentType::Send] or [PaymentType::Receive] payment PaymentType payment_type; + /// Composite status representing the overall status of the payment. + /// + /// If the tx has no associated swap, this reflects the onchain tx status (confirmed or not). + /// + /// If the tx has an associated swap, this is determined by the swap status (pending or complete). PaymentState status; + /// The details of a payment, depending on its [Payment::destination] `destination` and + /// [Payment::payment_type] `type`. PaymentDetails details; + /// 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 string? destination = null; string? tx_id = null; }; @@ -492,22 +759,75 @@ enum PaymentType { "Send", }; +/// The payment state of an individual payment. enum PaymentState { "Created", + /// ## Receive Swaps + /// + /// Covers the cases when + /// - the lockup tx is seen in the mempool or + /// - our claim tx is broadcast + /// + /// When the claim tx is broadcast, `claim_tx_id` is set in the swap. + /// + /// ## Send Swaps + /// + /// This is the status when our lockup tx was broadcast + /// + /// ## Chain Swaps + /// + /// This is the status when the user lockup tx was broadcast + /// + /// ## No swap data available + /// + /// If no associated swap is found, this indicates the underlying tx is not confirmed yet. "Pending", + /// ## Receive Swaps + /// + /// Covers the case when the claim tx is confirmed. + /// + /// ## Send and Chain Swaps + /// + /// This is the status when the claim tx is broadcast and we see it in the mempool. + /// + /// ## No swap data available + /// + /// If no associated swap is found, this indicates the underlying tx is confirmed. "Complete", + /// ## Receive Swaps + /// + /// This is the status when the swap failed for any reason and the Receive could not complete. + /// + /// ## Send and Chain Swaps + /// + /// This is the status when a swap refund was initiated and the refund tx is confirmed. "Failed", + /// ## Send and Outgoing Chain Swaps + /// + /// This covers the case when the swap state is still Created and the swap fails to reach the + /// Pending state in time. The TimedOut state indicates the lockup tx should never be broadcast. "TimedOut", + /// ## Incoming Chain Swaps + /// + /// This covers the case when the swap failed for any reason and there is a user lockup tx. + /// The swap in this case has to be manually refunded with a provided Bitcoin address "Refundable", + /// ## Send and Chain Swaps + /// + /// This is the status when a refund was initiated and/or our refund tx was broadcast + /// + /// When the refund tx is broadcast, `refund_tx_id` is set in the swap. "RefundPending", }; +/// Returned when calling [BindingLiquidSdk::list_refundables]. dictionary RefundableSwap { string swap_address; u32 timestamp; u64 amount_sat; }; +/// Returned when calling [BindingLiquidSdk::recommended_fees]. dictionary RecommendedFees { u64 fastest_fee; u64 half_hour_fee; @@ -516,28 +836,40 @@ dictionary RecommendedFees { u64 minimum_fee; }; +/// An argument when calling [BindingLiquidSdk::prepare_refund]. dictionary PrepareRefundRequest { + /// The address where the swap funds are locked up string swap_address; + /// The address to refund the swap funds to string refund_address; + /// The fee rate in sat/vB for the refund transaction u32 fee_rate_sat_per_vbyte; }; +/// Returned when calling [BindingLiquidSdk::prepare_refund]. dictionary PrepareRefundResponse { u32 tx_vsize; u64 tx_fee_sat; string? refund_tx_id = null; }; +/// An argument when calling [BindingLiquidSdk::refund]. dictionary RefundRequest { + /// The address where the swap funds are locked up string swap_address; + /// The address to refund the swap funds to string refund_address; + /// The fee rate in sat/vB for the refund transaction u32 fee_rate_sat_per_vbyte; }; +/// Returned when calling [BindingLiquidSdk::refund]. dictionary RefundResponse { string refund_tx_id; }; +/// Event emitted by the SDK. Add an [EventListener] by calling [BindingLiquidSdk::add_event_listener] +/// to listen for emitted events. [Enum] interface SdkEvent { PaymentFailed(Payment details); @@ -549,10 +881,12 @@ interface SdkEvent { Synced(); }; +/// Interface that can be used to receive [SdkEvent]s emitted by the SDK. callback interface EventListener { void on_event(SdkEvent e); }; +/// Interface that can be used to receive [LogEntry]s emitted by the SDK. callback interface Logger { void log(LogEntry l); }; @@ -563,115 +897,300 @@ dictionary LogEntry { }; namespace breez_sdk_liquid { + /// Initializes the SDK services and starts the background tasks. + /// This must be called to create the [BindingLiquidSdk] instance. + /// + /// # Arguments + /// + /// * `req` - the [ConnectRequest] containing: + /// * `mnemonic` - the Liquid wallet mnemonic + /// * `config` - the SDK [Config] [Throws=SdkError] BindingLiquidSdk connect(ConnectRequest req); + /// If used, this must be called before [connect]. [Throws=SdkError] void set_logger(Logger logger); + /// Get the full default [Config] for specific [LiquidNetwork]. Config default_config(LiquidNetwork network); + /// Parses a string into an [InputType]. [Throws=PaymentError] InputType parse(string input); + /// Parses a string into an [LNInvoice]. [Throws=PaymentError] LNInvoice parse_invoice(string input); }; interface BindingLiquidSdk { + /// Adds an event listener to the [LiquidSdk] instance, where all [SdkEvent]'s will be emitted to. + /// The event listener can be removed be calling [BindingLiquidSdk::remove_event_listener]. + /// + /// # Arguments + /// + /// * `listener` - The listener which is an implementation of the [EventListener] trait [Throws=SdkError] string add_event_listener(EventListener listener); + /// Removes an event listener from the [BindingLiquidSdk] instance. + /// + /// # Arguments + /// + /// * `id` - the event listener id returned by [BindingLiquidSdk::add_event_listener] [Throws=SdkError] void remove_event_listener(string id); + /// Get the wallet info, calculating the current pending and confirmed balances. [Throws=SdkError] GetInfoResponse get_info(); + /// Sign given message with the private key. Returns a zbase encoded signature. [Throws=SdkError] SignMessageResponse sign_message(SignMessageRequest req); + /// Check whether given message was signed by the given + /// pubkey and the signature (zbase encoded) is valid. [Throws=SdkError] CheckMessageResponse check_message(CheckMessageRequest req); + /// Prepares to pay a Lightning invoice via a submarine swap. + /// + /// # Arguments + /// + /// * `req` - the [PrepareSendRequest] containing: + /// * `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 [Throws=PaymentError] PrepareSendResponse prepare_send_payment(PrepareSendRequest req); + /// 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 + /// complete in this time + /// * [PaymentState::Complete] payment - if the payment was successfully completed in this time + /// + /// # Arguments + /// + /// * `req` - A [SendPaymentRequest], containing: + /// * `prepare_response` - the [PrepareSendResponse] returned by [BindingLiquidSdk::prepare_send_payment] + /// + /// # Errors + /// + /// * [PaymentError::PaymentTimeout] - if the payment could not be initiated in this time [Throws=PaymentError] SendPaymentResponse send_payment(SendPaymentRequest req); + /// Prepares to receive a Lightning payment via a reverse submarine swap. + /// + /// # Arguments + /// + /// * `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 [Throws=PaymentError] PrepareReceiveResponse prepare_receive_payment(PrepareReceiveRequest req); + /// Receive a Lightning payment via a reverse submarine swap, a chain swap or via direct Liquid + /// payment. + /// + /// # Arguments + /// + /// * `req` - the [ReceivePaymentRequest] containing: + /// * `prepare_response` - the [PrepareReceiveResponse] from calling [BindingLiquidSdk::prepare_receive_payment] + /// * `description` - the optional payment description + /// * `use_description_hash` - optional if true uses the hash of the description + /// + /// # Returns + /// + /// * A [ReceivePaymentResponse] containing: + /// * `destination` - the final destination to be paid by the payer, either a BIP21 URI (Liquid or Bitcoin), a Liquid address or an invoice [Throws=PaymentError] ReceivePaymentResponse receive_payment(ReceivePaymentRequest req); + /// Fetch the current payment limits for [BindingLiquidSdk::send_payment] and [BindingLiquidSdk::receive_payment]. [Throws=PaymentError] LightningPaymentLimitsResponse fetch_lightning_limits(); + /// Fetch the current payment limits for [BindingLiquidSdk::pay_onchain] and [BindingLiquidSdk::receive_onchain]. [Throws=PaymentError] OnchainPaymentLimitsResponse fetch_onchain_limits(); + /// Prepares to pay to a Bitcoin address via a chain swap. + /// + /// # Arguments + /// + /// * `req` - the [PreparePayOnchainRequest] containing: + /// * `amount` - which can be of two types: [PayOnchainAmount::Drain], which uses all funds, + /// and [PayOnchainAmount::Receiver], which sets the amount the receiver should receive + /// * `fee_rate_sat_per_vbyte` - the optional fee rate of the Bitcoin claim transaction. Defaults to the swapper estimated claim fee [Throws=PaymentError] PreparePayOnchainResponse prepare_pay_onchain(PreparePayOnchainRequest req); + /// Pays to a Bitcoin address via a chain swap. + /// + /// Depending on [Config]'s `payment_timeout_sec`, this function will return: + /// * [PaymentState::Pending] payment - if the payment could be initiated but didn't yet + /// complete in this time + /// * [PaymentState::Complete] payment - if the payment was successfully completed in this time + /// + /// # Arguments + /// + /// * `req` - the [PayOnchainRequest] containing: + /// * `address` - the Bitcoin address to pay to + /// * `prepare_response` - the [PreparePayOnchainResponse] from calling [BindingLiquidSdk::prepare_pay_onchain] + /// + /// # Errors + /// + /// * [PaymentError::PaymentTimeout] - if the payment could not be initiated in this time [Throws=PaymentError] SendPaymentResponse pay_onchain(PayOnchainRequest req); + /// Prepares to buy Bitcoin via a chain swap. + /// + /// # Arguments + /// + /// * `req` - the [PrepareBuyBitcoinRequest] containing: + /// * `provider` - the [BuyBitcoinProvider] to use + /// * `amount_sat` - the amount in satoshis to buy from the provider [Throws=PaymentError] PrepareBuyBitcoinResponse prepare_buy_bitcoin(PrepareBuyBitcoinRequest req); + /// Generate a URL to a third party provider used to buy Bitcoin via a chain swap. + /// + /// # Arguments + /// + /// * `req` - the [BuyBitcoinRequest] containing: + /// * `prepare_response` - the [PrepareBuyBitcoinResponse] from calling [BindingLiquidSdk::prepare_buy_bitcoin] + /// * `redirect_url` - the optional redirect URL the provider should redirect to after purchase [Throws=PaymentError] string buy_bitcoin(BuyBitcoinRequest req); + /// Lists the SDK payments in reverse chronological order, from newest to oldest. + /// The payments are determined based on onchain transactions and swaps. [Throws=PaymentError] sequence list_payments(ListPaymentsRequest req); + /// List all failed chain swaps that need to be refunded. + /// They can be refunded by calling [BindingLiquidSdk::prepare_refund] then [BindingLiquidSdk::refund]. [Throws=SdkError] sequence list_refundables(); + /// Prepares to refund a failed chain swap by calculating the refund transaction size and absolute fee. + /// + /// # Arguments + /// + /// * `req` - the [PrepareRefundRequest] containing: + /// * `swap_address` - the swap address to refund from [RefundableSwap::swap_address] + /// * `refund_address` - the Bitcoin address to refund to + /// * `fee_rate_sat_per_vbyte` - the fee rate at which to broadcast the refund transaction [Throws=SdkError] PrepareRefundResponse prepare_refund(PrepareRefundRequest req); + /// Refund a failed chain swap. + /// + /// # Arguments + /// + /// * `req` - the [RefundRequest] containing: + /// * `swap_address` - the swap address to refund from [RefundableSwap::swap_address] + /// * `refund_address` - the Bitcoin address to refund to + /// * `fee_rate_sat_per_vbyte` - the fee rate at which to broadcast the refund transaction [Throws=PaymentError] RefundResponse refund(RefundRequest req); + /// Rescans all expired chain swaps created from calling [BindingLiquidSdk::receive_onchain] within + /// the monitoring period to check if there are any confirmed funds available to refund. [Throws=SdkError] void rescan_onchain_swaps(); + /// Synchronizes the local state with the mempool and onchain data. [Throws=SdkError] void sync(); + /// Get the recommended Bitcoin fees based on the configured mempool.space instance. [Throws=SdkError] RecommendedFees recommended_fees(); + /// Backup the local state to the provided backup path. + /// + /// # Arguments + /// + /// * `req` - the [BackupRequest] containing: + /// * `backup_path` - the optional backup path. Defaults to [Config::working_dir] [Throws=SdkError] void backup(BackupRequest req); + /// Restores the local state from the provided backup path. + /// + /// # Arguments + /// + /// * `req` - the [RestoreRequest] containing: + /// * `backup_path` - the optional backup path. Defaults to [Config::working_dir] [Throws=SdkError] void restore(RestoreRequest req); + /// Disconnects the [BindingLiquidSdk] instance and stops the background tasks. [Throws=SdkError] void disconnect(); + /// Second step of LNURL-pay. The first step is [parse], which also validates the LNURL destination + /// and generates the [LnUrlPayRequest] payload needed here. + /// + /// This call will validate the `amount_msat` and `comment` parameters of `req` against the parameters + /// of the [LnUrlPayRequestData::req_data]. If they match the endpoint requirements, the LNURL payment + /// is made. [Throws=LnUrlPayError] LnUrlPayResult lnurl_pay(LnUrlPayRequest req); + /// Second step of LNURL-withdraw. The first step is [parse], which also validates the LNURL destination + /// and generates the [LnUrlWithdrawRequest] payload needed here. + /// + /// This call will validate the given `amount_msat` against the parameters + /// of the [LnUrlWithdrawRequestData::data]. If they match the endpoint requirements, the LNURL withdraw + /// request is made. A successful result here means the endpoint started the payment. [Throws=LnUrlWithdrawError] LnUrlWithdrawResult lnurl_withdraw(LnUrlWithdrawRequest req); + /// Third and last step of LNURL-auth. The first step is [parse], which also validates the LNURL destination + /// and generates the [LnUrlAuthRequestData] payload needed here. The second step is user approval of auth action. + /// + /// This call will sign the [LnUrlAuthRequestData::k1] of the `req_data` using the derived linking private key and DER-encodes the signature. + /// If they match the endpoint requirements, the LNURL auth request is made. A successful result here means the client signature is verified. [Throws=LnUrlAuthError] LnUrlCallbackStatus lnurl_auth(LnUrlAuthRequestData req_data); + /// Register for webhook callbacks at the given `webhook_url`. Each created swap after registering the + /// webhook will include the `webhook_url`. + /// + /// This method should be called every time the application is started and when the `webhook_url` changes. + /// For example, if the `webhook_url` contains a push notification token and the token changes after + /// the application was started, then this method should be called to register for callbacks at + /// the new correct `webhook_url`. To unregister a webhook call [BindingLiquidSdk::unregister_webhook]. [Throws=SdkError] void register_webhook(string webhook_url); + /// Unregister webhook callbacks. Each swap already created will continue to use the registered + /// `webhook_url` until complete. + /// + /// This can be called when callbacks are no longer needed or the `webhook_url` + /// has changed such that it needs unregistering. For example, the token is valid but the locale changes. + /// To register a webhook call [BindingLiquidSdk::register_webhook]. [Throws=SdkError] void unregister_webhook(); + /// Fetch live rates of fiat currencies, sorted by name. [Throws=SdkError] sequence fetch_fiat_rates(); + /// List all supported fiat currencies for which there is a known exchange rate. + /// List is sorted by the canonical name of the currency. [Throws=SdkError] sequence list_fiat_currencies(); }; diff --git a/lib/core/src/model.rs b/lib/core/src/model.rs index 18a56d9d0..eb38c8796 100644 --- a/lib/core/src/model.rs +++ b/lib/core/src/model.rs @@ -248,7 +248,7 @@ pub struct ReceivePaymentRequest { #[derive(Debug, Serialize)] pub struct ReceivePaymentResponse { /// Either a BIP21 URI (Liquid or Bitcoin), a Liquid address - /// or an invoice, depending on the [PrepareReceivePaymentResponse] parameters + /// or an invoice, depending on the [PrepareReceiveResponse] parameters pub destination: String, } diff --git a/packages/react-native/src/index.ts b/packages/react-native/src/index.ts index 69bc8f40f..bd9a0e533 100644 --- a/packages/react-native/src/index.ts +++ b/packages/react-native/src/index.ts @@ -19,15 +19,36 @@ const BreezSDKLiquid = NativeModules.RNBreezSDKLiquid const BreezSDKLiquidEmitter = new NativeEventEmitter(BreezSDKLiquid) +/** + * Wrapper for the decrypted {@link AesSuccessActionDataResult.DECRYPTED} payload + */ export interface AesSuccessActionDataDecrypted { + /** + * Contents description, up to 144 characters + */ description: string + /** + * Decrypted content + */ plaintext: string } +/** + * An argument when calling {@link backup}. + */ export interface BackupRequest { + /** + * Path to the backup. + * + * If not set, it defaults to 'backup.sql' for mainnet and 'backup-testnet.sql' for testnet. + * The file will be saved in {@link ConnectRequest}'s `dataDir`. + */ backupPath?: string } +/** + * Wrapped in a {@link InputType.BITCOIN_ADDRESS}, this is the result of {@link parse} when given a plain or BIP-21 BTC address. + */ export interface BitcoinAddressData { address: string network: Network @@ -36,38 +57,95 @@ export interface BitcoinAddressData { message?: string } +/** + * An argument when calling {@link buyBitcoin}. + */ export interface BuyBitcoinRequest { prepareResponse: PrepareBuyBitcoinResponse + /** + * The optional URL to redirect to after completing the buy. + * + * For Moonpay, see + */ redirectUrl?: string } +/** + * An argument when calling {@link checkMessage}. + */ export interface CheckMessageRequest { + /** + * The message that was signed. + */ message: string + /** + * The public key of the node that signed the message. + */ pubkey: string + /** + * The zbase encoded signature to verify. + */ signature: string } +/** + * Returned when calling {@link checkMessage}. + */ export interface CheckMessageResponse { + /** + * Boolean value indicating whether the signature covers the message and + * was signed by the given pubkey. + */ isValid: boolean } +/** + * Configuration for the Liquid SDK + */ export interface Config { liquidElectrumUrl: string bitcoinElectrumUrl: string + /** + * The mempool.space API URL, has to be in the format: https://mempool.space/api + */ mempoolspaceUrl: string + /** + * Directory in which all SDK files (DB, log, cache) are stored. + * + * Prefix can be a relative or absolute path to this directory. + */ workingDir: string network: LiquidNetwork + /** + * Send payment timeout. See {@link sendPayment} + */ paymentTimeoutSec: number + /** + * Zero-conf minimum accepted fee-rate in millisatoshis per vbyte + */ zeroConfMinFeeRateMsat: number + /** + * Maximum amount in satoshi to accept zero-conf payments with + * Defaults to [crate::receive_swap::DEFAULT_ZERO_CONF_MAX_SAT] + */ zeroConfMaxAmountSat?: number + /** + * The Breez API key used for making requests to their mempool service + */ breezApiKey?: string } +/** + * An argument when calling {@link connect}. + */ export interface ConnectRequest { config: Config mnemonic: string } +/** + * Details about a supported currency in the fiat rate feed + */ export interface CurrencyInfo { name: string fractionSize: number @@ -83,13 +161,28 @@ export interface FiatCurrency { info: CurrencyInfo } +/** + * Returned when calling {@link getInfo}. + */ export interface GetInfoResponse { + /** + * Usable balance. This is the confirmed onchain balance minus `pendingSendSat`. + */ balanceSat: number + /** + * Amount that is being used for ongoing Send swaps + */ pendingSendSat: number + /** + * Incoming amount that is pending from ongoing Receive swaps + */ pendingReceiveSat: number pubkey: string } +/** + * Wrapper for a BOLT11 LN invoice + */ export interface LnInvoice { bolt11: string network: Network @@ -105,17 +198,32 @@ export interface LnInvoice { minFinalCltvExpiryDelta: number } +/** + * Returned when calling {@link fetchLightningLimits}. + */ export interface LightningPaymentLimitsResponse { + /** + * Amount limits for a Send Payment to be valid + */ send: Limits + /** + * Amount limits for a Receive Payment to be valid + */ receive: Limits } +/** + * The minimum and maximum in satoshis of a Lightning or onchain payment. + */ export interface Limits { minSat: number maxSat: number maxZeroConfSat: number } +/** + * Wrapped in a {@link InputType.LIQUID_ADDRESS}, this is the result of {@link parse} when given a plain or BIP-21 Liquid address. + */ export interface LiquidAddressData { address: string network: Network @@ -125,21 +233,54 @@ export interface LiquidAddressData { message?: string } +/** + * An argument when calling {@link listPayments}. + */ export interface ListPaymentsRequest { filters?: PaymentType[] + /** + * Epoch time, in seconds + */ fromTimestamp?: number + /** + * Epoch time, in seconds + */ toTimestamp?: number offset?: number limit?: number } +/** + * Wrapped in a {@link InputType.LN_URL_AUTH}, this is the result of {@link parse} when given a LNURL-auth endpoint. + * + * It represents the endpoint's parameters for the LNURL workflow. + * + * See + */ export interface LnUrlAuthRequestData { + /** + * Hex encoded 32 bytes of challenge + */ k1: string + /** + * Indicates the domain of the LNURL-auth service, to be shown to the user when asking for + * auth confirmation, as per LUD-04 spec. + */ domain: string + /** + * Indicates the URL of the LNURL-auth service, including the query arguments. This will be + * extended with the signed challenge and the linking key, then called in the second step of the workflow. + */ url: string + /** + * When available, one of: register, login, link, auth + */ action?: string } +/** + * Wrapped in a {@link InputType.LN_URL_ERROR}, this represents a LNURL-endpoint error. + */ export interface LnUrlErrorData { reason: string } @@ -149,23 +290,84 @@ export interface LnUrlPayErrorData { reason: string } +/** + * Represents a LNURL-pay request. + */ export interface LnUrlPayRequest { + /** + * The {@link LnUrlPayRequestData} returned by {@link parse} + */ data: LnUrlPayRequestData + /** + * The amount in millisatoshis for this payment + */ amountMsat: number + /** + * An optional comment for this payment + */ comment?: string + /** + * The external label or identifier of the {@link Payment} + */ paymentLabel?: string + /** + * Validates that, if there is a URL success action, the URL domain matches + * the LNURL callback domain. Defaults to `true` + */ validateSuccessActionUrl?: boolean } +/** + * Wrapped in a {@link InputType.LN_URL_PAY}, this is the result of {@link parse} when given a LNURL-pay endpoint. + * + * It represents the endpoint's parameters for the LNURL workflow. + * + * See + */ export interface LnUrlPayRequestData { callback: string + /** + * The minimum amount, in millisats, that this LNURL-pay endpoint accepts + */ minSendable: number + /** + * The maximum amount, in millisats, that this LNURL-pay endpoint accepts + */ maxSendable: number + /** + * As per LUD-06, `metadata` is a raw string (e.g. a json representation of the inner map) + */ metadataStr: string + /** + * The comment length accepted by this endpoint + * + * See + */ commentAllowed: number + /** + * Indicates the domain of the LNURL-pay service, to be shown to the user when asking for + * payment input, as per LUD-06 spec. + * + * Note: this is not the domain of the callback, but the domain of the LNURL-pay endpoint. + */ domain: string + /** + * Value indicating whether the recipient supports Nostr Zaps through NIP-57. + * + * See + */ allowsNostr: boolean + /** + * Optional recipient's lnurl provider's Nostr pubkey for NIP-57. If it exists it should be a + * valid BIP 340 public key in hex. + * + * See + * See + */ nostrPubkey?: string + /** + * If sending to a LN Address, this will be filled. + */ lnAddress?: string } @@ -175,16 +377,42 @@ export interface LnUrlPaySuccessData { } export interface LnUrlWithdrawRequest { + /** + * Request data containing information on how to call the lnurl withdraw + * endpoint. Typically retrieved by calling {@link parse} on a lnurl withdraw + * input. + */ data: LnUrlWithdrawRequestData + /** + * The amount to withdraw from the lnurl withdraw endpoint. Must be between + * `minWithdrawable` and `maxWithdrawable`. + */ amountMsat: number + /** + * Optional description that will be put in the payment request for the + * lnurl withdraw endpoint. + */ description?: string } +/** + * Wrapped in a {@link InputType.LN_URL_WITHDRAW}, this is the result of {@link parse} when given a LNURL-withdraw endpoint. + * + * It represents the endpoint's parameters for the LNURL workflow. + * + * See + */ export interface LnUrlWithdrawRequestData { callback: string k1: string defaultDescription: string + /** + * The minimum amount, in millisats, that this LNURL-withdraw endpoint accepts + */ minWithdrawable: number + /** + * The maximum amount, in millisats, that this LNURL-withdraw endpoint accepts + */ maxWithdrawable: number } @@ -192,12 +420,18 @@ export interface LnUrlWithdrawSuccessData { invoice: LnInvoice } +/** + * Locale-specific settings for the representation of a currency + */ export interface LocaleOverrides { locale: string spacing?: number symbol: SymbolType } +/** + * Localized name of a currency + */ export interface LocalizedName { locale: string name: string @@ -208,101 +442,238 @@ export interface LogEntry { level: string } +/** + * Wrapper for the {@link SuccessActionProcessed.MESSAGE} payload + */ export interface MessageSuccessActionData { message: string } +/** + * Returned when calling {@link fetchOnchainLimits}. + */ export interface OnchainPaymentLimitsResponse { + /** + * Amount limits for a Send Onchain Payment to be valid + */ send: Limits + /** + * Amount limits for a Receive Onchain Payment to be valid + */ receive: Limits } +/** + * An argument when calling {@link payOnchain}. + */ export interface PayOnchainRequest { address: string prepareResponse: PreparePayOnchainResponse } +/** + * Represents an SDK payment. + * + * By default, this is an onchain tx. It may represent a swap, if swap metadata is available. + */ export interface Payment { + /** + * 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 + * in time when the underlying tx was included in a block. If there is no associated swap + * available and the underlying tx is not yet confirmed, the value is 'now()'. + */ timestamp: number + /** + * The payment amount, which corresponds to the onchain tx amount. + * + * In case of an outbound payment (Send), this is the payer amount. Otherwise it's the receiver amount. + */ amountSat: number + /** + * Represents the fees paid by this wallet for this payment. + * + * ### Swaps + * If there is an associated Send Swap, these fees represent the total fees paid by this wallet + * (the sender). It is the difference between the amount that was sent and the amount received. + * + * If there is an associated Receive Swap, these fees represent the total fees paid by this wallet + * (the receiver). It is also the difference between the amount that was sent and the amount received. + * + * ### Pure onchain txs + * If no swap is associated with this payment: + * - for Send payments, this is the onchain tx fee + * - for Receive payments, this is zero + */ feesSat: number + /** + * If it is a {@link PaymentType.SEND} or {@link PaymentType.RECEIVE} payment + */ paymentType: PaymentType + /** + * Composite status representing the overall status of the payment. + * + * If the tx has no associated swap, this reflects the onchain tx status (confirmed or not). + * + * If the tx has an associated swap, this is determined by the swap status (pending or complete). + */ status: PaymentState + /** + * The details of a payment, depending on its {@link Payment.destination} `destination` and + * {@link Payment.paymentType} `type`. + */ details: PaymentDetails + /** + * 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 + */ destination?: string txId?: string } +/** + * An argument when calling {@link prepareBuyBitcoin}. + */ export interface PrepareBuyBitcoinRequest { provider: BuyBitcoinProvider amountSat: number } +/** + * Returned when calling {@link prepareBuyBitcoin}. + */ export interface PrepareBuyBitcoinResponse { provider: BuyBitcoinProvider amountSat: number feesSat: number } +/** + * An argument when calling {@link preparePayOnchain}. + */ export interface PreparePayOnchainRequest { amount: PayOnchainAmount + /** + * The optional fee rate of the Bitcoin claim transaction in sat/vB. Defaults to the swapper estimated claim fee. + */ feeRateSatPerVbyte?: number } +/** + * Returned when calling {@link preparePayOnchain}. + */ export interface PreparePayOnchainResponse { receiverAmountSat: number claimFeesSat: number totalFeesSat: number } +/** + * An argument when calling {@link prepareReceivePayment}. + */ export interface PrepareReceiveRequest { paymentMethod: PaymentMethod payerAmountSat?: number } +/** + * Returned when calling {@link prepareReceivePayment}. + */ export interface PrepareReceiveResponse { payerAmountSat?: number paymentMethod: PaymentMethod feesSat: number } +/** + * An argument when calling {@link prepareRefund}. + */ export interface PrepareRefundRequest { + /** + * The address where the swap funds are locked up + */ swapAddress: string + /** + * The address to refund the swap funds to + */ refundAddress: string + /** + * The fee rate in sat/vB for the refund transaction + */ feeRateSatPerVbyte: number } +/** + * Returned when calling {@link prepareRefund}. + */ export interface PrepareRefundResponse { txVsize: number txFeeSat: number refundTxId?: string } +/** + * An argument when calling {@link prepareSendPayment}. + */ export interface PrepareSendRequest { + /** + * The destination we intend to pay to. + * Supports BIP21 URIs, BOLT11 invoices and Liquid addresses + */ destination: string + /** + * Should only be set when paying directly onchain or to a BIP21 URI + * where no amount is specified + */ amountSat?: number } +/** + * Returned when calling {@link prepareSendPayment}. + */ export interface PrepareSendResponse { destination: SendDestination feesSat: number } +/** + * Denominator in an exchange rate + */ export interface Rate { coin: string value: number } +/** + * An argument when calling {@link receivePayment}. + */ export interface ReceivePaymentRequest { prepareResponse: PrepareReceiveResponse + /** + * The description for this payment request. + */ description?: string + /** + * If set to true, then the hash of the description will be used. + */ useDescriptionHash?: boolean } +/** + * Returned when calling {@link receivePayment}. + */ export interface ReceivePaymentResponse { + /** + * Either a BIP21 URI (Liquid or Bitcoin), a Liquid address + * or an invoice, depending on the {@link PrepareReceiveResponse} parameters + */ destination: string } +/** + * Returned when calling {@link recommendedFees}. + */ export interface RecommendedFees { fastestFee: number halfHourFee: number @@ -311,56 +682,116 @@ export interface RecommendedFees { minimumFee: number } +/** + * An argument when calling {@link refund}. + */ export interface RefundRequest { + /** + * The address where the swap funds are locked up + */ swapAddress: string + /** + * The address to refund the swap funds to + */ refundAddress: string + /** + * The fee rate in sat/vB for the refund transaction + */ feeRateSatPerVbyte: number } +/** + * Returned when calling {@link refund}. + */ export interface RefundResponse { refundTxId: string } +/** + * Returned when calling {@link listRefundables}. + */ export interface RefundableSwap { swapAddress: string timestamp: number amountSat: number } +/** + * An argument when calling {@link restore}. + */ export interface RestoreRequest { backupPath?: string } +/** + * A route hint for a LN payment + */ export interface RouteHint { hops: RouteHintHop[] } +/** + * Details of a specific hop in a larger route hint + */ export interface RouteHintHop { + /** + * The node id of the non-target end of the route + */ srcNodeId: string + /** + * The short channel id of this channel + */ shortChannelId: string + /** + * The fees which must be paid to use this channel + */ feesBaseMsat: number feesProportionalMillionths: number + /** + * The difference in CLTV values between this node and the next node + */ cltvExpiryDelta: number + /** + * The minimum value, in msat, which must be relayed to the next hop + */ htlcMinimumMsat?: number + /** + * The maximum value in msat available for routing with a single HTLC + */ htlcMaximumMsat?: number } +/** + * An argument when calling {@link sendPayment}. + */ export interface SendPaymentRequest { prepareResponse: PrepareSendResponse } +/** + * Returned when calling {@link sendPayment}. + */ export interface SendPaymentResponse { payment: Payment } +/** + * An argument when calling {@link signMessage}. + */ export interface SignMessageRequest { message: string } +/** + * Returned when calling {@link signMessage}. + */ export interface SignMessageResponse { signature: string } +/** + * Settings for the symbol representation of a currency + */ export interface SymbolType { grapheme?: string template?: string @@ -368,9 +799,23 @@ export interface SymbolType { position?: number } +/** + * Wrapper for the {@link SuccessActionProcessed.URL} payload + */ export interface UrlSuccessActionData { + /** + * Contents description, up to 144 characters + */ description: string + /** + * URL of the success action + */ url: string + /** + * Indicates the success URL domain matches the LNURL callback domain. + * + * See + */ matchesCallbackDomain: boolean } @@ -379,6 +824,9 @@ export enum AesSuccessActionDataResultVariant { ERROR_STATUS = "errorStatus" } +/** + * Result of decryption of {@link SuccessActionProcessed.AES} payload + */ export type AesSuccessActionDataResult = { type: AesSuccessActionDataResultVariant.DECRYPTED, data: AesSuccessActionDataDecrypted @@ -387,22 +835,70 @@ export type AesSuccessActionDataResult = { reason: string } +/** + * An argument of {@link PrepareBuyBitcoinRequest} when calling {@link prepareBuyBitcoin}. + */ export enum BuyBitcoinProvider { MOONPAY = "moonpay" } export enum InputTypeVariant { + /** + * # Supported standards + * + * - plain on-chain BTC address + * - BIP21 + */ BITCOIN_ADDRESS = "bitcoinAddress", + /** + * # Supported standards + * + * - plain on-chain liquid address + * - BIP21 on liquid/liquidtestnet + */ LIQUID_ADDRESS = "liquidAddress", BOLT11 = "bolt11", NODE_ID = "nodeId", URL = "url", + /** + * # Supported standards + * + * - LUD-01 LNURL bech32 encoding + * - LUD-06 `payRequest` spec + * - LUD-16 LN Address + * - LUD-17 Support for lnurlp prefix with non-bech32-encoded LNURL URLs + */ LN_URL_PAY = "lnUrlPay", + /** + * # Supported standards + * + * - LUD-01 LNURL bech32 encoding + * - LUD-03 `withdrawRequest` spec + * - LUD-17 Support for lnurlw prefix with non-bech32-encoded LNURL URLs + * + * # Not supported (yet) + * + * - LUD-14 `balanceCheck`: reusable `withdrawRequest`s + * - LUD-19 Pay link discoverable from withdraw link + */ LN_URL_WITHDRAW = "lnUrlWithdraw", + /** + * # Supported standards + * + * - LUD-01 LNURL bech32 encoding + * - LUD-04 `auth` base spec + * - LUD-17 Support for keyauth prefix with non-bech32-encoded LNURL URLs + */ LN_URL_AUTH = "lnUrlAuth", + /** + * Error returned by the LNURL endpoint + */ LN_URL_ERROR = "lnUrlError" } +/** + * Different kinds of inputs supported by {@link parse}, including any relevant details extracted from the input + */ export type InputType = { type: InputTypeVariant.BITCOIN_ADDRESS, address: BitcoinAddressData @@ -432,8 +928,18 @@ export type InputType = { data: LnUrlErrorData } +/** + * Network chosen for this Liquid SDK instance. Note that it represents both the Liquid and the + * Bitcoin network used. + */ export enum LiquidNetwork { + /** + * Mainnet Bitcoin and Liquid chains + */ MAINNET = "mainnet", + /** + * Testnet Bitcoin and Liquid chains + */ TESTNET = "testnet" } @@ -442,6 +948,17 @@ export enum LnUrlCallbackStatusVariant { ERROR_STATUS = "errorStatus" } +/** + * Contains the result of the entire LNURL interaction, as reported by the LNURL endpoint. + * + * * {@link LnUrlCallbackStatus.OK} indicates the interaction with the endpoint was valid, and the endpoint + * - started to pay the invoice asynchronously in the case of LNURL-withdraw, + * - verified the client signature in the case of LNURL-auth + * * {@link LnUrlCallbackStatus.ERROR_STATUS} indicates a generic issue the LNURL endpoint encountered, including a freetext + * description of the reason. + * + * Both cases are described in LUD-03 & LUD-04: + */ export type LnUrlCallbackStatus = { type: LnUrlCallbackStatusVariant.OK } | { @@ -455,6 +972,19 @@ export enum LnUrlPayResultVariant { PAY_ERROR = "payError" } +/** + * Contains the result of the entire LNURL-pay interaction, as reported by the LNURL endpoint. + * + * * {@link LnUrlPayResult.ENDPOINT_SUCCESS} indicates the payment is complete. The endpoint may return a {@link SuccessActionProcessed}, + * in which case, the wallet has to present it to the user as described in + * + * + * * {@link LnUrlPayResult.ENDPOINT_ERROR} indicates a generic issue the LNURL endpoint encountered, including a freetext + * field with the reason. + * + * * {@link LnUrlPayResult.PAY_ERROR} 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. + */ export type LnUrlPayResult = { type: LnUrlPayResultVariant.ENDPOINT_SUCCESS, data: LnUrlPaySuccessData @@ -472,6 +1002,9 @@ export enum LnUrlWithdrawResultVariant { ERROR_STATUS = "errorStatus" } +/** + * {@link LnUrlCallbackStatus} specific to LNURL-withdraw, where the success case contains the invoice. + */ export type LnUrlWithdrawResult = { type: LnUrlWithdrawResultVariant.OK, data: LnUrlWithdrawSuccessData @@ -483,7 +1016,13 @@ export type LnUrlWithdrawResult = { data: LnUrlErrorData } +/** + * The different supported bitcoin networks + */ export enum Network { + /** + * Mainnet + */ BITCOIN = "bitcoin", TESTNET = "testnet", SIGNET = "signet", @@ -491,7 +1030,13 @@ export enum Network { } export enum PayOnchainAmountVariant { + /** + * The amount in satoshi that will be received + */ RECEIVER = "receiver", + /** + * Indicates that all available funds should be sent + */ DRAIN = "drain" } @@ -503,11 +1048,23 @@ export type PayOnchainAmount = { } export enum PaymentDetailsVariant { + /** + * Swapping to or from Lightning + */ LIGHTNING = "lightning", + /** + * Direct onchain payment to a Liquid address + */ LIQUID = "liquid", + /** + * Swapping to or from the Bitcoin chain + */ BITCOIN = "bitcoin" } +/** + * The specific details of a payment, depending on its type + */ export type PaymentDetails = { type: PaymentDetailsVariant.LIGHTNING, swapId: string @@ -528,19 +1085,87 @@ export type PaymentDetails = { refundTxAmountSat?: number } +/** + * The send/receive methods supported by the SDK + */ export enum PaymentMethod { LIGHTNING = "lightning", BITCOIN_ADDRESS = "bitcoinAddress", LIQUID_ADDRESS = "liquidAddress" } +/** + * The payment state of an individual payment. + */ export enum PaymentState { CREATED = "created", + /** + * ## Receive Swaps + * + * Covers the cases when + * - the lockup tx is seen in the mempool or + * - our claim tx is broadcast + * + * When the claim tx is broadcast, `claimTxId` is set in the swap. + * + * ## Send Swaps + * + * This is the status when our lockup tx was broadcast + * + * ## Chain Swaps + * + * This is the status when the user lockup tx was broadcast + * + * ## No swap data available + * + * If no associated swap is found, this indicates the underlying tx is not confirmed yet. + */ PENDING = "pending", + /** + * ## Receive Swaps + * + * Covers the case when the claim tx is confirmed. + * + * ## Send and Chain Swaps + * + * This is the status when the claim tx is broadcast and we see it in the mempool. + * + * ## No swap data available + * + * If no associated swap is found, this indicates the underlying tx is confirmed. + */ COMPLETE = "complete", + /** + * ## Receive Swaps + * + * This is the status when the swap failed for any reason and the Receive could not complete. + * + * ## Send and Chain Swaps + * + * This is the status when a swap refund was initiated and the refund tx is confirmed. + */ FAILED = "failed", + /** + * ## Send and Outgoing Chain Swaps + * + * This covers the case when the swap state is still Created and the swap fails to reach the + * Pending state in time. The TimedOut state indicates the lockup tx should never be broadcast. + */ TIMED_OUT = "timedOut", + /** + * ## Incoming Chain Swaps + * + * This covers the case when the swap failed for any reason and there is a user lockup tx. + * The swap in this case has to be manually refunded with a provided Bitcoin address + */ REFUNDABLE = "refundable", + /** + * ## Send and Chain Swaps + * + * This is the status when a refund was initiated and/or our refund tx was broadcast + * + * When the refund tx is broadcast, `refundTxId` is set in the swap. + */ REFUND_PENDING = "refundPending" } @@ -559,6 +1184,10 @@ export enum SdkEventVariant { SYNCED = "synced" } +/** + * Event emitted by the SDK. Add an {@link EventListener} by calling {@link addEventListener} + * to listen for emitted events. + */ export type SdkEvent = { type: SdkEventVariant.PAYMENT_FAILED, details: Payment @@ -586,6 +1215,9 @@ export enum SendDestinationVariant { BOLT11 = "bolt11" } +/** + * Specifies the supported destinations which can be payed by the SDK + */ export type SendDestination = { type: SendDestinationVariant.LIQUID_ADDRESS, addressData: LiquidAddressData @@ -611,15 +1243,39 @@ export type SuccessActionProcessed = { data: UrlSuccessActionData } +/** + * Interface that can be used to receive {@link SdkEvent}s emitted by the SDK. + */ export type EventListener = (e: SdkEvent) => void +/** + * Interface that can be used to receive {@link LogEntry}s emitted by the SDK. + */ export type Logger = (logEntry: LogEntry) => void +/** + * Initializes the SDK services and starts the background tasks. + * This must be called to create the {@link BindingLiquidSdk} instance. + * + * # Arguments + * + * * `req` - the {@link ConnectRequest} containing: + * * `mnemonic` - the Liquid wallet mnemonic + * * `config` - the SDK {@link Config} + */ export const connect = async (req: ConnectRequest): Promise => { const response = await BreezSDKLiquid.connect(req) return response } +/** + * Adds an event listener to the [LiquidSdk] instance, where all {@link SdkEvent}'s will be emitted to. + * The event listener can be removed be calling {@link removeEventListener}. + * + * # Arguments + * + * * `listener` - The listener which is an implementation of the {@link EventListener} trait + */ export const addEventListener = async (listener: EventListener): Promise => { const response = await BreezSDKLiquid.addEventListener() BreezSDKLiquidEmitter.addListener(`event-${response}`, listener) @@ -627,6 +1283,9 @@ export const addEventListener = async (listener: EventListener): Promise return response } +/** + * If used, this must be called before {@link connect}. + */ export const setLogger = async (logger: Logger): Promise => { const subscription = BreezSDKLiquidEmitter.addListener("breezSdkLiquidLog", logger) @@ -637,165 +1296,403 @@ export const setLogger = async (logger: Logger): Promise => return subscription } +/** + * Get the full default {@link Config} for specific {@link LiquidNetwork}. + */ export const defaultConfig = async (network: LiquidNetwork): Promise => { const response = await BreezSDKLiquid.defaultConfig(network) return response } +/** + * Parses a string into an {@link InputType}. + */ export const parse = async (input: string): Promise => { const response = await BreezSDKLiquid.parse(input) return response } +/** + * Parses a string into an {@link LnInvoice}. + */ export const parseInvoice = async (input: string): Promise => { const response = await BreezSDKLiquid.parseInvoice(input) return response } +/** + * Backup the local state to the provided backup path. + * + * # Arguments + * + * * `req` - the {@link BackupRequest} containing: + * * `backupPath` - the optional backup path. Defaults to {@link Config.workingDir} + */ export const backup = async (req: BackupRequest): Promise => { await BreezSDKLiquid.backup(req) } +/** + * Generate a URL to a third party provider used to buy Bitcoin via a chain swap. + * + * # Arguments + * + * * `req` - the {@link BuyBitcoinRequest} containing: + * * `prepareResponse` - the {@link PrepareBuyBitcoinResponse} from calling {@link prepareBuyBitcoin} + * * `redirectUrl` - the optional redirect URL the provider should redirect to after purchase + */ export const buyBitcoin = async (req: BuyBitcoinRequest): Promise => { const response = await BreezSDKLiquid.buyBitcoin(req) return response } +/** + * Check whether given message was signed by the given + * pubkey and the signature (zbase encoded) is valid. + */ export const checkMessage = async (req: CheckMessageRequest): Promise => { const response = await BreezSDKLiquid.checkMessage(req) return response } +/** + * Disconnects the {@link BindingLiquidSdk} instance and stops the background tasks. + */ export const disconnect = async (): Promise => { await BreezSDKLiquid.disconnect() } +/** + * Fetch live rates of fiat currencies, sorted by name. + */ export const fetchFiatRates = async (): Promise => { const response = await BreezSDKLiquid.fetchFiatRates() return response } +/** + * Fetch the current payment limits for {@link sendPayment} and {@link receivePayment}. + */ export const fetchLightningLimits = async (): Promise => { const response = await BreezSDKLiquid.fetchLightningLimits() return response } +/** + * Fetch the current payment limits for {@link payOnchain} and {@link receiveOnchain}. + */ export const fetchOnchainLimits = async (): Promise => { const response = await BreezSDKLiquid.fetchOnchainLimits() return response } +/** + * Get the wallet info, calculating the current pending and confirmed balances. + */ export const getInfo = async (): Promise => { const response = await BreezSDKLiquid.getInfo() return response } +/** + * List all supported fiat currencies for which there is a known exchange rate. + * List is sorted by the canonical name of the currency. + */ export const listFiatCurrencies = async (): Promise => { const response = await BreezSDKLiquid.listFiatCurrencies() return response } +/** + * Lists the SDK payments in reverse chronological order, from newest to oldest. + * The payments are determined based on onchain transactions and swaps. + */ export const listPayments = async (req: ListPaymentsRequest): Promise => { const response = await BreezSDKLiquid.listPayments(req) return response } +/** + * List all failed chain swaps that need to be refunded. + * They can be refunded by calling {@link prepareRefund} then {@link refund}. + */ export const listRefundables = async (): Promise => { const response = await BreezSDKLiquid.listRefundables() return response } +/** + * Third and last step of LNURL-auth. The first step is {@link parse}, which also validates the LNURL destination + * and generates the {@link LnUrlAuthRequestData} payload needed here. The second step is user approval of auth action. + * + * This call will sign the {@link LnUrlAuthRequestData.k1} of the `reqData` using the derived linking private key and DER-encodes the signature. + * If they match the endpoint requirements, the LNURL auth request is made. A successful result here means the client signature is verified. + */ export const lnurlAuth = async (reqData: LnUrlAuthRequestData): Promise => { const response = await BreezSDKLiquid.lnurlAuth(reqData) return response } +/** + * Second step of LNURL-pay. The first step is {@link parse}, which also validates the LNURL destination + * and generates the {@link LnUrlPayRequest} payload needed here. + * + * This call will validate the `amountMsat` and `comment` parameters of `req` against the parameters + * of the {@link LnUrlPayRequestData.reqData}. If they match the endpoint requirements, the LNURL payment + * is made. + */ export const lnurlPay = async (req: LnUrlPayRequest): Promise => { const response = await BreezSDKLiquid.lnurlPay(req) return response } +/** + * Second step of LNURL-withdraw. The first step is {@link parse}, which also validates the LNURL destination + * and generates the {@link LnUrlWithdrawRequest} payload needed here. + * + * This call will validate the given `amountMsat` against the parameters + * of the {@link LnUrlWithdrawRequestData.data}. If they match the endpoint requirements, the LNURL withdraw + * request is made. A successful result here means the endpoint started the payment. + */ export const lnurlWithdraw = async (req: LnUrlWithdrawRequest): Promise => { const response = await BreezSDKLiquid.lnurlWithdraw(req) return response } +/** + * Pays to a Bitcoin address via a chain swap. + * + * Depending on {@link Config}'s `paymentTimeoutSec`, this function will return: + * * {@link PaymentState.PENDING} payment - if the payment could be initiated but didn't yet + * complete in this time + * * {@link PaymentState.COMPLETE} payment - if the payment was successfully completed in this time + * + * # Arguments + * + * * `req` - the {@link PayOnchainRequest} containing: + * * `address` - the Bitcoin address to pay to + * * `prepareResponse` - the {@link PreparePayOnchainResponse} from calling {@link preparePayOnchain} + * + * # Errors + * + * * {@link PaymentError.PAYMENT_TIMEOUT} - if the payment could not be initiated in this time + */ export const payOnchain = async (req: PayOnchainRequest): Promise => { const response = await BreezSDKLiquid.payOnchain(req) return response } +/** + * Prepares to buy Bitcoin via a chain swap. + * + * # Arguments + * + * * `req` - the {@link PrepareBuyBitcoinRequest} containing: + * * `provider` - the {@link BuyBitcoinProvider} to use + * * `amountSat` - the amount in satoshis to buy from the provider + */ export const prepareBuyBitcoin = async (req: PrepareBuyBitcoinRequest): Promise => { const response = await BreezSDKLiquid.prepareBuyBitcoin(req) return response } +/** + * Prepares to pay to a Bitcoin address via a chain swap. + * + * # Arguments + * + * * `req` - the {@link PreparePayOnchainRequest} containing: + * * `amount` - which can be of two types: {@link PayOnchainAmount.DRAIN}, which uses all funds, + * and {@link PayOnchainAmount.RECEIVER}, which sets the amount the receiver should receive + * * `feeRateSatPerVbyte` - the optional fee rate of the Bitcoin claim transaction. Defaults to the swapper estimated claim fee + */ export const preparePayOnchain = async (req: PreparePayOnchainRequest): Promise => { const response = await BreezSDKLiquid.preparePayOnchain(req) return response } +/** + * Prepares to receive a Lightning payment via a reverse submarine swap. + * + * # Arguments + * + * * `req` - the {@link PrepareReceiveRequest} containing: + * * `payerAmountSat` - the amount in satoshis to be paid by the payer + * * `paymentMethod` - the supported payment methods; either an invoice, a Liquid address or a Bitcoin address + */ export const prepareReceivePayment = async (req: PrepareReceiveRequest): Promise => { const response = await BreezSDKLiquid.prepareReceivePayment(req) return response } +/** + * Prepares to refund a failed chain swap by calculating the refund transaction size and absolute fee. + * + * # Arguments + * + * * `req` - the {@link PrepareRefundRequest} containing: + * * `swapAddress` - the swap address to refund from {@link RefundableSwap.swapAddress} + * * `refundAddress` - the Bitcoin address to refund to + * * `feeRateSatPerVbyte` - the fee rate at which to broadcast the refund transaction + */ export const prepareRefund = async (req: PrepareRefundRequest): Promise => { const response = await BreezSDKLiquid.prepareRefund(req) return response } +/** + * Prepares to pay a Lightning invoice via a submarine swap. + * + * # Arguments + * + * * `req` - the {@link PrepareSendRequest} containing: + * * `destination` - Either a Liquid BIP21 URI/address or a BOLT11 invoice + * * `amountSat` - Should only be specified when paying directly onchain or via amount-less BIP21 + * + * # Returns + * Returns a {@link PrepareSendResponse} containing: + * * `destination` - the parsed destination, of type {@link SendDestination} + * * `feesSat` - the additional fees which will be paid by the sender + */ export const prepareSendPayment = async (req: PrepareSendRequest): Promise => { const response = await BreezSDKLiquid.prepareSendPayment(req) return response } +/** + * Receive a Lightning payment via a reverse submarine swap, a chain swap or via direct Liquid + * payment. + * + * # Arguments + * + * * `req` - the {@link ReceivePaymentRequest} containing: + * * `prepareResponse` - the {@link PrepareReceiveResponse} from calling {@link prepareReceivePayment} + * * `description` - the optional payment description + * * `useDescriptionHash` - optional if true uses the hash of the description + * + * # Returns + * + * * A {@link ReceivePaymentResponse} containing: + * * `destination` - the final destination to be paid by the payer, either a BIP21 URI (Liquid or Bitcoin), a Liquid address or an invoice + */ export const receivePayment = async (req: ReceivePaymentRequest): Promise => { const response = await BreezSDKLiquid.receivePayment(req) return response } +/** + * Get the recommended Bitcoin fees based on the configured mempool.space instance. + */ export const recommendedFees = async (): Promise => { const response = await BreezSDKLiquid.recommendedFees() return response } +/** + * Refund a failed chain swap. + * + * # Arguments + * + * * `req` - the {@link RefundRequest} containing: + * * `swapAddress` - the swap address to refund from {@link RefundableSwap.swapAddress} + * * `refundAddress` - the Bitcoin address to refund to + * * `feeRateSatPerVbyte` - the fee rate at which to broadcast the refund transaction + */ export const refund = async (req: RefundRequest): Promise => { const response = await BreezSDKLiquid.refund(req) return response } +/** + * Register for webhook callbacks at the given `webhookUrl`. Each created swap after registering the + * webhook will include the `webhookUrl`. + * + * This method should be called every time the application is started and when the `webhookUrl` changes. + * For example, if the `webhookUrl` contains a push notification token and the token changes after + * the application was started, then this method should be called to register for callbacks at + * the new correct `webhookUrl`. To unregister a webhook call {@link unregisterWebhook}. + */ export const registerWebhook = async (webhookUrl: string): Promise => { await BreezSDKLiquid.registerWebhook(webhookUrl) } +/** + * Removes an event listener from the {@link BindingLiquidSdk} instance. + * + * # Arguments + * + * * `id` - the event listener id returned by {@link addEventListener} + */ export const removeEventListener = async (id: string): Promise => { await BreezSDKLiquid.removeEventListener(id) } +/** + * Rescans all expired chain swaps created from calling {@link receiveOnchain} within + * the monitoring period to check if there are any confirmed funds available to refund. + */ export const rescanOnchainSwaps = async (): Promise => { await BreezSDKLiquid.rescanOnchainSwaps() } +/** + * Restores the local state from the provided backup path. + * + * # Arguments + * + * * `req` - the {@link RestoreRequest} containing: + * * `backupPath` - the optional backup path. Defaults to {@link Config.workingDir} + */ export const restore = async (req: RestoreRequest): Promise => { await BreezSDKLiquid.restore(req) } +/** + * Either pays a Lightning invoice via a submarine swap or sends funds directly to an address. + * + * Depending on {@link Config}'s `paymentTimeoutSec`, this function will return: + * * {@link PaymentState.PENDING} payment - if the payment could be initiated but didn't yet + * complete in this time + * * {@link PaymentState.COMPLETE} payment - if the payment was successfully completed in this time + * + * # Arguments + * + * * `req` - A {@link SendPaymentRequest}, containing: + * * `prepareResponse` - the {@link PrepareSendResponse} returned by {@link prepareSendPayment} + * + * # Errors + * + * * {@link PaymentError.PAYMENT_TIMEOUT} - if the payment could not be initiated in this time + */ export const sendPayment = async (req: SendPaymentRequest): Promise => { const response = await BreezSDKLiquid.sendPayment(req) return response } +/** + * Sign given message with the private key. Returns a zbase encoded signature. + */ export const signMessage = async (req: SignMessageRequest): Promise => { const response = await BreezSDKLiquid.signMessage(req) return response } +/** + * Synchronizes the local state with the mempool and onchain data. + */ export const sync = async (): Promise => { await BreezSDKLiquid.sync() } +/** + * Unregister webhook callbacks. Each swap already created will continue to use the registered + * `webhookUrl` until complete. + * + * This can be called when callbacks are no longer needed or the `webhookUrl` + * has changed such that it needs unregistering. For example, the token is valid but the locale changes. + * To register a webhook call {@link registerWebhook}. + */ export const unregisterWebhook = async (): Promise => { await BreezSDKLiquid.unregisterWebhook() }