Crate breez_sdk_core

Source
Expand description

§Breez SDK

The Breez SDK enables mobile developers to integrate Lightning and bitcoin payments into their apps with a very shallow learning curve. The use cases are endless – from social apps that want to integrate tipping between users to content-creation apps interested in adding bitcoin monetization. Crucially, this SDK is an end-to-end, non-custodial, drop-in solution powered by Greenlight, a built-in LSP, on-chain interoperability, third-party fiat on-ramps, and other services users and operators need.

The Breez SDK provides the following services:

  • Sending payments (via various protocols such as: bolt11, keysend, lnurl-pay, lightning address, etc.)
  • Receiving payments (via various protocols such as: bolt11, lnurl-withdraw, etc.)
  • Fetching node status (e.g. balance, max allow to pay, max allow to receive, on-chain balance, etc.)
  • Connecting to a new or existing node.

§Getting Started

First, make sure you have your API Key and Invite Code ready (see API Key and Invite Code section below).

The following code initialize the SDK and make it ready to be used:

let mnemonic = Mnemonic::generate_in(Language::English, 12)?;
let seed = mnemonic.to_seed("");
let invite_code = Some("...".into());

let mut config = BreezServices::default_config(
    EnvironmentType::Production,
    "your API key".into(),
    breez_sdk_core::NodeConfig::Greenlight {
        config: GreenlightNodeConfig { partner_credentials: None, invite_code },
    },
);

// Customize the config object according to your needs
config.working_dir = "path to an existing directory".into();

// Connect to the Breez SDK make it ready for use
let sdk = BreezServices::connect(
   config,
   seed.to_vec(),        
   Box::new(AppEventListener {}),
)
.await?;

We can now receive payments

let invoice = sdk.receive_payment(3000, "Invoice for 3000 sats".into()).await?;

or make payments

let bolt11 = "...";
sdk.send_payment(bolt11.into(), Some(3000)).await?;

At any point we can fetch our balance from the Greenlight node

if let Some(node_state) = sdk.node_info()? {
    let balance_ln = node_state.channels_balance_msat;
    let balance_onchain = node_state.onchain_balance_msat;
}

or fetch other useful infos, like the current mempool RecommendedFees

let fees: RecommendedFees = sdk.recommended_fees().await?;

These different types of operations are described below in more detail.

§A. Initializing the SDK

There are two simple steps necessary to initialize the SDK:

  1. BreezServices::default_config to construct the sdk configuration
  2. BreezServices::connect to connect to your node and start all required Breez SDK services

The first step takes the EnvironmentType and NodeConfig as arguments. Although you can create your own config from scratch it is recommended to use the BreezServices::default_config method and customize it according to your needs. Once the NodeConfig is created it is passed to the BreezServices::connect method along with the seed and and implementation of EventListener which is used to notify the caller of SDK events.

Now your SDK is ready to be used.

§B. Sending and receiving Lightning payments

Supported BOLT11 operations are

§C. Receiving an on-chain transaction (swap-in)

§D. Sending to an on-chain address (swap-out)

§E. Using LNURL

  1. parse the LNURL endpoint URL to get the workflow parameters.
  2. After getting the user input or confirmation, complete the workflow with BreezServices::lnurl_pay or BreezServices::lnurl_withdraw.

§F. Supporting fiat currencies

§G. Connecting to an LSP

§H. Utilities

Use parse to parse generic input. The input can come from the user, from a clicked link or from a QR code. The resulting InputType will tell you what the input is and how to treat it, as well as present relevant payload data in a structured form.

§Bindings

  • C#
  • Dart
  • Go
  • Kotlin
  • Python
  • React-Native
  • Swift

§API Key and Invite Code

You will need an API Key to use the SDK, as well as an Invite Code when you create a new node.

To get both of them, please contact Breez via email at contact@breez.technology or at https://breez.technology/#contact-us-form

§Support

Join this telegram group.

Modules§

binding
Bindings for the Dart integration
bitcoin
Rust Bitcoin Library
error
grpc
input_parser
invoice
lightning
Rust-Lightning, not Rusty’s Lightning!
lightning_invoice
This crate provides data structures to represent lightning BOLT11 invoices and functions to create, encode and decode these. If you just want to use the standard en-/decoding functionality this should get you started:
lnurl
moonpay
specs
tonic_wrap
utils

Macros§

ensure_sdk
with_connection_retry
Executes the given grpc call function. If an error is returned that indicates the connection broke, the call is tried again.

Structs§

AesSuccessActionData
Payload of the AES success action, as received from the LNURL endpoint
AesSuccessActionDataDecrypted
Wrapper for the decrypted AesSuccessActionData payload
ApiKeyInterceptor
BackupFailedData
BackupStatus
BitcoinAddressData
Wrapped in a [BitcoinAddress], this is the result of parse when given a plain or BIP-21 BTC address.
BreezServer
BreezServices
BreezServices is a facade and the single entry point for the SDK.
BuyBitcoinRequest
BuyBitcoinResponse
CallbackResponse
Channel
Lightning channel
CheckMessageRequest
Request to check a message was signed by a specific node id.
CheckMessageResponse
Response to a CheckMessageRequest
ClosedChannelPaymentDetails
Represents the funds that were on the user side of the channel at the time it was closed.
Config
Configuration for the Breez Services
ConfigureNodeRequest
Represents a configure node request.
ConnectRequest
Represents a connect request.
CurrencyInfo
Details about a supported currency in the fiat rate feed
CustomMessage
ExternalInputParser
Configuration for an external input parser
FiatCurrency
Wrapper around the CurrencyInfo of a fiat currency
FullReverseSwapInfo
Details of past or ongoing reverse swaps, as stored in the Breez local DB
GreenlightCredentials
Client-specific credentials to connect to and manage a Greenlight node in the cloud
GreenlightDeviceCredentials
Device credentials used to authenticate to Greenlight with the current device.
GreenlightNodeConfig
Htlc
InvoicePaidDetails
Details of an invoice that has been paid, included as payload in an emitted BreezEvent
LNInvoice
Wrapper for a BOLT11 LN invoice
LNOffer
ListPaymentsRequest
Represents a list payments request.
ListSwapsRequest
LnOfferBlindedPath
LnPaymentDetails
Details of a LN payment, as included in a Payment
LnUrlAuthRequestData
Wrapped in a [LnUrlAuth], this is the result of [parse] when given a LNURL-auth endpoint.
LnUrlErrorData
Wrapped in a [LnUrlError], this represents a LNURL-endpoint error.
LnUrlPayErrorData
LnUrlPayRequest
Represents a LNURL-pay request.
LnUrlPayRequestData
Wrapped in a [LnUrlPay], this is the result of parse when given a LNURL-pay endpoint.
LnUrlPaySuccessData
LnUrlWithdrawRequest
LnUrlWithdrawRequestData
Wrapped in a [LnUrlWithdraw], this is the result of parse when given a LNURL-withdraw endpoint.
LnUrlWithdrawSuccessData
LocaleOverrides
Locale-specific settings for the representation of a currency
LocalizedName
Localized name of a currency
LogEntry
Internal SDK log entry
LspInformation
Details of supported LSP
MaxChannelAmount
MessageSuccessActionData
MetadataFilter
A metadata filter which can be applied when retrieving the transaction list
MetadataItem
Key-value pair in the LnUrlPayRequestData, as returned by the LNURL-pay endpoint
MoonpayProvider
NodeState
The node state of a Greenlight LN node running in the cloud.
OnchainPaymentLimitsResponse
OpenChannelFeeRequest
OpenChannelFeeResponse
OpeningFeeParams
Dynamic fee parameters offered by the LSP for opening a new channel.
OpeningFeeParamsMenu
See OpeningFeeParamsMenu::try_from
PayOnchainRequest
PayOnchainResponse
Payment
Represents a payment, including its PaymentType and PaymentDetails
PaymentExternalInfo
Represents a payments external information.
PaymentFailedData
PaymentPath
PaymentPathEdge
PaymentResponse
Represents a payment response.
PrepareOnchainPaymentRequest
See ReverseSwapFeesRequest
PrepareOnchainPaymentResponse
Contains fields describing the reverse swap parameters (see ReverseSwapPairInfo), as well as the resulting send and receive amounts.
PrepareRedeemOnchainFundsRequest
We need to prepare a redeem_onchain_funds transaction to know what fee will be charged in satoshis. This model holds the request data which consists of the address to redeem on-chain funds to and the fee rate in. satoshis per vbyte which will be converted to absolute satoshis.
PrepareRedeemOnchainFundsResponse
We need to prepare a redeem_onchain_funds transaction to know what a fee it will be charged in satoshis this model holds the response data, which consists of the weight and the absolute fee in sats
PrepareRefundRequest
PrepareRefundResponse
Rate
Denominator in an exchange rate
ReceiveOnchainRequest
ReceivePaymentRequest
Represents a receive payment request.
ReceivePaymentResponse
Represents a receive payment response.
RecommendedFees
Wrapper containing the result of the recommended fees query, in sat/vByte, based on mempool.space data
RedeemOnchainFundsRequest
RedeemOnchainFundsResponse
RefundRequest
RefundResponse
ReportPaymentFailureDetails
ReqwestRestClient
ReverseSwapFeesRequest
ReverseSwapInfo
Simplified version of FullReverseSwapInfo, containing only the user-relevant fields
ReverseSwapInfoCached
ReverseSwapPairInfo
Details about the reverse swap fees and parameters, at this point in time
RouteHint
A route hint for a LN payment
RouteHintHop
Details of a specific hop in a larger route hint
SendPaymentRequest
Represents a send payment request.
SendPaymentResponse
Represents a send payment response.
SendSpontaneousPaymentRequest
Represents a send spontaneous payment request.
ServiceConnectivityError
ServiceHealthCheckResponse
Represents a service health check response.
SignMessageRequest
Request to sign a message with the node’s private key.
SignMessageResponse
Response to a SignMessageRequest.
StaticBackupRequest
StaticBackupResponse
Swap
Summary of an ongoing swap
SwapInfo
Represents the details of an on-going swap.
Symbol
Settings for the symbol representation of a currency
SyncResponse
Internal response to a [crate::node_api::NodeAPI::pull_changed] call
TlvEntry
Represents a TLV entry for a keysend payment.
UnspentTransactionOutput
UTXO known to the LN node
UrlSuccessActionData

Enums§

AesSuccessActionDataResult
Result of decryption of AesSuccessActionData payload
Amount
BreezEvent
Event emitted by the SDK. To listen for and react to these events, use an EventListener when initializing the BreezServices.
BuyBitcoinProvider
Different providers will demand different behaviours when the user is trying to buy bitcoin.
ChannelState
State of a Lightning channel
DynamicFeeType
EnvironmentType
Indicates the different kinds of supported environments for crate::BreezServices.
FeeratePreset
Different types of supported feerates
HealthCheckStatus
Indicates the different service health check statuses.
InputType
Different kinds of inputs supported by parse, including any relevant details extracted from the input
InvoiceError
LnUrlAuthError
Error returned by [crate::breez_services::BreezServices::lnurl_auth]
LnUrlCallbackStatus
Contains the result of the entire LNURL interaction, as reported by the LNURL endpoint.
LnUrlError
LnUrlPayError
Error returned by [crate::breez_services::BreezServices::lnurl_pay]
LnUrlRequestData
Generic struct containing the possible LNURL payloads returned when contacting a LNURL endpoint
LnUrlWithdrawError
LnUrlWithdrawResult
LnUrlCallbackStatus specific to LNURL-withdraw, where the success case contains the invoice.
Network
The different supported bitcoin networks
NodeConfig
NodeCredentials
PaymentDetails
Wrapper for the different types of payments
PaymentStatus
The status of a payment
PaymentType
Different types of supported payments
PaymentTypeFilter
Different types of supported filters which can be applied when retrieving the transaction list
ReportIssueRequest
Represents a report issue request.
ReverseSwapStatus
The possible statuses of a reverse swap, from the Breez SDK perspective.
ServiceConnectivityErrorKind
SuccessAction
Supported success action types
SuccessActionProcessed
SuccessAction where contents are ready to be consumed by the caller
SwapAmountType
SwapStatus
The status of a swap
URISerializationError
ValidatedCallbackResponse

Constants§

ESTIMATED_CLAIM_TX_VSIZE
ESTIMATED_LOCKUP_TX_VSIZE
INVOICE_PAYMENT_FEE_EXPIRY_SECONDS
SWAP_PAYMENT_FEE_EXPIRY_SECONDS

Statics§

PRODUCTION_BREEZSERVER_URL
STAGING_BREEZSERVER_URL

Traits§

BuyBitcoinProviderApi
EventListener
Trait that can be used to react to various BreezEvents emitted by the SDK.
FiatAPI
Trait covering fiat-related functionality
LnurlAuthSigner
LogStream
LspAPI
Trait covering LSP-related functionality
RestClient
SupportAPI
Trait covering support-related functionality
SwapperAPI
Trait covering functionality involving swaps

Functions§

add_routing_hints
build_pay_callback_url
build_withdraw_callback_url
get_and_check_success
get_derivation_path
invoice_pubkey
Try to take payee pubkey from the tagged fields, if doesn’t exist recover it from the signature
mnemonic_to_seed
Attempts to convert the phrase to a mnemonic, then to a seed.
parse
Parses generic user input, typically pasted from clipboard or scanned from a QR.
parse_invoice
Parse a BOLT11 payment request and return a structure contains the parsed fields.
parse_json
parse_with_rest_client
perform_lnurl_auth
Performs the third and last step of LNURL-auth, as per https://github.com/lnurl/luds/blob/luds/04.md
validate_invoice
validate_lnurl_pay
Validates invoice and performs the second and last step of LNURL-pay, as per https://github.com/lnurl/luds/blob/luds/06.md
validate_lnurl_withdraw
Validates invoice and performs the second and last step of LNURL-withdraw, as per https://github.com/lnurl/luds/blob/luds/03.md
validate_network
validate_request
validate_user_input

Type Aliases§

Aes256CbcDec
Aes256CbcEnc
InvoiceResult
LnUrlResult